Generics in Java
Lecture - 25
Generics in java Templates in C++
Types
• Generic class
• Generic methods
Symbol to specify
Generic parameters <>
is ????
Syntax
BaseType <Type> obj=new BaseType <Type>();
Primitive data types like int, char or double cannot
be used for defining the parameter type
Generic Class
Making a class generic i.e a
class can accept and adapt
different datatypes
Generic Class – Example 1
class Test<T> class Main
{ {
T obj; public static void main (String[] args)
Test(T obj) {
{ Test <Integer> Obj1 = new Test<Integer>(15);
this.obj = obj; System.out.println(Obj1.getObject());
} Now <T> will make the Test <String> Obj2=new Test<String>("Face");
public T getObject() class Test take Integers System.out.println(Obj2.getObject());
{ }
return this.obj; }
}
Generic Class – Example 1
class Test<T> class Main
{ {
T obj; public static void main (String[] args)
Test(T obj) {
{ Now <T> will make the Test <Integer> Obj1 = new Test<Integer>(15);
this.obj = obj; class Test take Strings System.out.println(Obj1.getObject());
} Test <String> Obj2=new Test<String>("Face");
public T getObject() System.out.println(Obj2.getObject());
{ }
So we can use the same class
return this.obj;
for integers and }Strings
} This isthan
rather Generic
writingclass
two Output:
} different classes 15
Face
Generic Class
Is it possible to pass
multiple Type parameters in
Generic classes ????
Generic Class
class Test<T, U> }
{ }
T obj1; class Main
U obj2; {
Test(T obj1, U obj2) public static void main (String[] args)
{ {
this.obj1 = obj1; Test <String, Integer> obj = new
Test<String,Integer> ("Face",15);
this.obj2 = obj2;
Now, obj.print();
} <T> will make the class Test take
}
public void print() Strings and
}
{ <U> will make the class Test take
Output:
System.out.println(obj1); Integers
Face
System.out.println(obj2); 15
Generic Functions or Generic Methods
• Functions that can be called with different types of arguments
Making a method generic
i.e a function can accept
and adapt different data
types
Generic method - Example
public class Test t.genericDisplay(1.0);
{ }
<T> void genericDisplay(T element) }
{
System.out.println(element);
Now,
}
<T> will make the method
public static void main(String[] args) accept
accept
it as
it as
double
Strings
int
{
Test t=new Test();
Output:
t.genericDisplay(100); Output:
Output:
100
100
t.genericDisplay("Face"); Face
100
Face
1.0
Advantages of Generics
• Code reusability
• Type safety - Generics make errors to appear compile time than at
run time (It’s always better to know problems in your code at compile
time rather than making your code fail at run time)