0% found this document useful (0 votes)
318 views17 pages

CS8392 - OOPs - UNIT - 4 - PPT - 4.2

The document discusses Java generics programming. It introduces generics and lists some key advantages like type safety, eliminating type casting, and compile-time checking. It provides examples of generics applied to classes like Box<T> and methods like printArray<E>. Bounded type parameters are explained which allow restricting the kinds of types passed to a type parameter. Restrictions on generics are also covered like not instantiating with primitives or creating instances of type parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
318 views17 pages

CS8392 - OOPs - UNIT - 4 - PPT - 4.2

The document discusses Java generics programming. It introduces generics and lists some key advantages like type safety, eliminating type casting, and compile-time checking. It provides examples of generics applied to classes like Box<T> and methods like printArray<E>. Bounded type parameters are explained which allow restricting the kinds of types passed to a type parameter. Restrictions on generics are also covered like not instantiating with primitives or creating instances of type parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CS 8392

OBJECT ORIENTED
PROGRAMMING

VASANTHA KUMAR V,AP/CSE


GENERIC PROGRAMMING

• The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
• It makes the code stable by detecting the bugs at compile time.
ADVANTAGE OF JAVA GENERICS

1. Type-safety: We can hold only a single type of objects in generics. It doesn't allow to store
other objects.
2. Type casting is not required: There is no need to typecast the object.
3. Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime.
ADVANTAGE OF JAVA GENERICS
Type-safety: We can hold only a single type of objects in generics. It doesn't allow to store other
objects.
EXAMPLE :
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
ADVANTAGE OF JAVA GENERICS
Type casting is not required: There is no need to typecast the object.
EXAMPLE :
• List list = new ArrayList();
• list.add("hello");
• String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
• List<String> list = new ArrayList<String>();
• list.add("hello");
• String s = list.get(0);
ADVANTAGE OF JAVA GENERICS
Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
EXAMPLE :
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
GENERICS - EXAMPLE
import java.util.*;
class TestGenerics1{
public static void main(String args[]){ Iterator<String> itr=list.iterator();
ArrayList<String> list=new ArrayList<String>();
while(itr.hasNext()){
list.add("rahul"); System.out.println(itr.next());
list.add("jai"); }
//list.add(32);//compile time error }
String s=list.get(1);//type casting is not required }
System.out.println("element is: "+s);
GENERIC CLASSES
• A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.
• The type parameter section of a generic class can have one or more type parameters separated
by commas.
The common type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
GENERIC CLASSES
Syntax :
public class Box<T> {
private T t;
}
Where
• Box − Box is a generic class.
• T − The generic type parameter passed to generic class. It can take any Object.
• t − Instance of generic type T.
The T is a type parameter passed to the generic class Box and should be passed when a Box object
is created.
GENERIC CLASSES
public class GenericsTester { class Box<T> {
public static void main(String[] args) { private T t;
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>(); public void add(T t)
{
integerBox.add(new Integer(10)); this.t = t;
stringBox.add(new String("Hello World")); }

System.out.printf("Integer Value :%d\n", public T get() {


integerBox.get()); return t;
System.out.printf("String Value :%s\n", }
stringBox.get()); }
}
}
GENERICS - METHODS
Single generic method declaration that can be called with arguments of different types. Based on the types
of the arguments passed to the generic method, the compiler handles each method call appropriately.
Following are the rules to define Generic Methods −
• All generic method declarations have a type parameter section delimited by angle brackets (< and >) that
precedes the method's return type ( < E >- example).
• Each type parameter section contains one or more type parameters separated by commas. A type
parameter, also known as a type variable, is an identifier that specifies a generic type name.
• The type parameters can be used to declare the return type and act as placeholders for the types of the
arguments passed to the generic method, which are known as actual type arguments.
• A generic method's body is declared like that of any other method. Note that type parameters can
represent only reference types, not primitive types (like int, double and char).
GENERICS - METHODS
public class GenericMethodTest { System.out.println("Array
public static < E > void printArray( E[] inputArray ) integerArray contains:");
{ printArray(intArray);
for(E element : inputArray) { System.out.println("\nA
System.out.printf("%s ", element); rray doubleArray contains:");
} printArray(doubleArray)
System.out.println(); ; System.out.println(
} "\nArray characterArray
public static void main(String args[]) { contains:");
// Create arrays of Integer, Double and Character printArray(charArray);
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O'
};
GENERICS - BOUNDED TYPE PARAMETERS

• There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a
type parameter.
• For example, a method that operates on numbers might only want to accept instances of Number or
its subclasses.
GENERICS - BOUNDED TYPE PARAMETERS
public class MaximumTest {
// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z) {


T max = x; // assume x is initially the largest

if(y.compareTo(max) > 0) {
max = y; // y is the largest so far
}

if(z.compareTo(max) > 0) {
max = z; // z is the largest now
}
return max; // returns the largest object
}
GENERICS - BOUNDED TYPE PARAMETERS
public static void main(String args[])
{
System.out.printf("Max of %d, %d and %d is %d\n\n",3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",6.6, 8.8, 7.7,


maximum( 6.6, 8.8, 7.7 ));

System.out.printf("Max of %s, %s and %s is %s\n","pear","apple",


"orange", maximum("pear", "apple", "orange"));

}
}
RESTRICTIONS ON GENERICS
To use Java generics effectively, you must consider the following restrictions:
• Cannot Instantiate Generic Types with Primitive Types
• Cannot Create Instances of Type Parameters
• Cannot Declare Static Fields Whose Types are Type Parameters
• Cannot Use Casts or instanceof With Parameterized Types
• Cannot Create Arrays of Parameterized Types
• Cannot Create, Catch, or Throw Objects of Parameterized Types
• Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the
Same Raw Type
THANK YOU

You might also like