0% found this document useful (0 votes)
60 views15 pages

Generic Programming in Java

Generic programming in Java allows the creation of generic classes, interfaces, and methods that can work with different data types. Generics use type parameters like <T> to make a class or method reusable for multiple types. At compile time, type safety is ensured, but the generic type information is erased at runtime. This allows generics to avoid casting and increase code reuse while maintaining type safety. Some key elements of Java generics include generic classes and methods, wildcard types, bounds, and type erasure.

Uploaded by

Navin s
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
60 views15 pages

Generic Programming in Java

Generic programming in Java allows the creation of generic classes, interfaces, and methods that can work with different data types. Generics use type parameters like <T> to make a class or method reusable for multiple types. At compile time, type safety is ensured, but the generic type information is erased at runtime. This allows generics to avoid casting and increase code reuse while maintaining type safety. Some key elements of Java generics include generic classes and methods, wildcard types, bounds, and type erasure.

Uploaded by

Navin s
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 15

Generic Programming In

Java
Java Generics
• The Java Generics allows us to create a single class, interface, and method
that can be used with different types of data.
• In other words, Generics is a concept where you can enable a class,
interface and, method, accept all reference types as parameters.
• Java generics is used to achieve parametric polymorphism.
• Generics uses the diamond syntax <Type>.
• Generics in Java is similar to Templates used in C++.
• Generic programming is a style of programming in which algorithms are
written to be specified later types that are instantiated when needed for
specific types provided as parameter.
Generic Classes
class Gen<T> {
private T data;
public Gen (T data) {
this.data = data;
}
public T getData() {
return this.data;
}
}

class Main {
public static void main(String[] args) {
Gen<Integer> intObj = new Gen<Integer>(5);
System.out.println("Class returns: " + intObj.getData());
Gen<String> stringObj = new Gen<Integer>("Java Programming");
System.out.println("Class returns: " + stringObj.getData());
}
}
Generic Class with 2 Parameter
class TwoGen<T, V>{ public class Main {
T ob1; public static void main(String[] args) {
V ob2; TwoGen<Integer, String> Obj1 = new TwoGen<Integer, String>(22, "apple");
TwoGen(T o1, V o2){ TwoGen<Integer, Double> Obj2 = new TwoGen<Integer, Double>(52, 3.14);
ob1 = o1; Obj1.showTypes();
ob2 = o2; Obj2.showTypes();
} int a = Obj2.getob1();
void showTypes(){ System.out.println(a);
System.out.println("Type of T is "+ ob1.getClass()); double b = Obj2.getob2();
System.out.println("Type of V is "+ ob2.getClass()); System.out.println(b);
} }
T getob1(){ }
return ob1;
}
V getob2(){
return ob2;
}
}
Generic Method
public class Main {
public static < E > void printArray( E[] inputArray ) {
for(E element : inputArray) {
System.out.print(element+ " ");
}
System.out.println();
}

public static void main(String[] args) {


Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray);
System.out.println("\nArray characterArray contains:");
printArray(charArray);
}
}
Generic Bounds
There are cases where we want to restrict the type of objects that can be passed as parameter.
In such cases bounds are used.
Syntax: <T extends ClassName>
Extends can refer to both a class and interface.
class rec<T extends Number>{
T num;
rec(T n){
num = n;
}
double reciprocal(){
return 1/num.doubleValue();
}
}
class Main {
public static void main(String[] args) {
rec<Float> Obj1 = new rec<Float>(5.89F);
rec<Integer> Obj2 = new rec<Integer>(25);
System.out.println(Obj1.reciprocal());
System.out.println(Obj2.reciprocal()); }
}
Generic Constructors
class GenCons{ It is possible to create generic
private double val; constructors.
<T extends Number> GenСons (T arg) {
val = arg.doubleValue();
}
void showval() {
System.out.println("val: " + val);
}
}

class GenConsDemo {
public static void main(String args[]) {
GenСons test = new GenСons (100);
GenСons test2 = new GenСons (123.5F);
test. showval();
test2.showval();
}
}
Wildcard Arguments
• The question mark (?) is known as the wildcard in generic programming
. It represents an unknown type.
• The wildcard can be used in a variety of situations such as the type of a
parameter, field, or local variable; sometimes as a return type.
• We can use a wildcard as a type of a parameter, field, return type, or
local variable.
• It is not allowed to use a wildcard as a type argument for a generic
method invocation, a generic class instance creation.
• There are 3 ways of using wildcard:
• Unbounded - ?
• Upper bounded - ? extends Type
• Lower bounded - ? super Type
Type Erasure
• Generics are used for tighter type checks at compile time and to
provide a generic programming. To implement generic behavior, java
compiler apply type erasure.
• Type erasure is a process in which compiler replaces a generic
parameter with actual class or bridge method. In type erasure,
compiler ensures that no extra classes are created and there is no
runtime overhead.
• Type Erasure rules
• Replace type parameters in generic type with their bound if bounded type
parameters are used.
• Replace type parameters in generic type with Object if unbounded type
parameters are used.
• Insert type casts to preserve type safety.
• Generate bridge methods to keep polymorphism in extended generic types.
public class Node<T> { public class Node {

private T data; private Object data;


private Node<T> next; private Node next;

public Node(T data, Node<T> next) { public Node(Object data, Node next) {
this.data = data; this.data = data;
this.next = next; this.next = next;
} }
public T getData() { return data; } public Object getData() { return data; }
} }

public class Node<T extends Comparable<T>> { public class Node {

private T data; private Comparable data;


private Node<T> next; private Node next;

public Node(T data, Node<T> next) { public Node(Comparable data, Node next) {
this.data = data; this.data = data;
this.next = next; this.next = next;
} }
public T getData() { return data; } public Comparable getData() { return data; }
} }
Advantages
• Increases code reusability.
• A Java compiler applies strong type checking to generic
code and issues errors if the code violates type safety.
Fixing compile-time errors is easier than fixing runtime
errors, which can be difficult to find.
• There is no need to typecast the object.
• By using generics, we can implement algorithms that work
on different types of objects and at the same they are type
safe too. The java collection framework that contains data
structures and algorithms implement generics.
//Without Generics – No type safety //With Generics – Type safety
List list = new ArrayList(); List<String> list = new ArrayList<String>();    
list.add(10); list.add(“java");    
list.add(“abc"); list.add(12.6); //compile time error

//Without Generics - Type casting //With Generics – No Type casting


List list = new ArrayList();     List<String> list = new ArrayList<String>();
list.add("hello");     list.add("hello");    
String s = (String) list.get(0); String s = list.get(0);    
Restrictions and Limitations
class Gen<T>{
T ob;
• Can not create generics with primitive types. Gen(){
• Can not create a instance of type parameter. ob = new T();
}
//Error

• Static members and static method can not use type }

parameter. But static generic method can be created.


Class Gen<T>{
• We can not create an array of type parameter. static T ob; //Error
}
• We can not create generic class exceptions as they
don’t extend Throwable class.
Class Gen<T extends Number>{
T vals[];
Gen(T o, T[] nums){
vals = new T[]; //Error
}
}
References
• https://docs.oracle.com/javase/tutorial/java/generics/index.html
• Java The complete reference, 9th edition by Herbert Schildt
• Core Java Volume I Fundamentals, 11th edition by Cay S Horstmann
Thank You

You might also like