Generics in Java

Why we need Generics?

Generics in java is a concept which allows the users to choose the reference type that a method, constructor of a class accepts. By the usage of generics, we can enable a class interface and method accepts all types as parameters. Please check out the below example:

Class Generics
{
Integer work;
Generics(Integer work){
this.work=work;
}
public void display() {
system.out.println(“Working hours: “this.work);
}
}
public class GenericsMain 
{
public static void main (String args[] ) 
{
Generics generic=new Generics(10);
generic.display();
}
}

Generic class

A class is generic if it declares one or more type variables. In the example we are using the E type parameter to create the generic class of specific type.

Class Worker {
E obg;
Void add (E obg){ this.obg=obg;}
E get(){return obg;}
}

Generic Interfaces

A generic interface has a name and a formal type parameter E. The other parts of the interface use E as they would use an actual type e.g String

Public interface Worker 
{ 
void move(E e, String code); 
E getTerm(); 
String getMove(); 
} 

Generic Methods and Constructors

Constructors can also be generic. Even non-generic class can have generic constructors. Also constructors are like methods but without return types.

Class WorkerClass
{
Public NonGenericClass(E tm)
{.
E tmp=tm;
System.out.println(tmp);
}
}
Public class Generic
{
Public static void main(String[] args)  

Worker wr1.  =  new WorkerClass(10)
Worker wr2   =  new.WorkerClass(“ed”)
Worker wr3   =. New WorkerClass(3.2)
}
}

Bounded Types

Bounded types are introduced in generics. Using generics types, you can make the objects of generic class to have data of specific derived types.

Class Worker
{.
E wr;
public Worker(E tm)
{
this.tm=tm;
}
Public E getE()
{
Return tm
}
}

Wildcard Arguments

Wildcards is a mechanism in Java aimed for making it possible to cast a collection of a certain class, e.g E, to a collection of a subclass or superclass of E.

Static boolean Worker(List tm) {
Return tm.add(remove(0));
}

Generics and Their Inheritance

Inheritance is an OOP’s concept and generics are a CLR feature that allows you specify type parameters at compile-time for types that expose them.

Inheritance allows me to create one type:

Class Name{}

And then later create another type that extends Pen

Class FullName: Name{}

Type Erasure

Type erasure is a process where generic parameters are replaced by actual class or method by compiler. In type erasure, compiler gives surity that no extra classes are created and there is no runtime overhead.

Class Worker {
E tmp;
Worker (W wr)
{
Tmp=wr;
}
E get()
{
Return tmp;
}
}

After compile the is replaced like below:

Class Worker {
String tmp;
Worker (String wr)
 {
    Tmp=wr;
 }
String get()
{
return tmp;
}
}

Leave a Reply