What is generics?

In the earlier version of java generics was not there.It was added in jdk5.
The term Generics means parameterized types. Parameterized types are important because they enable you to create classes, interfaces and methods in which a the type of data upon which they operate is specified as parameter. A class, interface or method operates on a parameterized type is called generics.
Means it is possible to create classes, interfaces and methods which are type independent.
One can define a single algorithm which is independent of data, then apply the same algorithm to any kind of data types without any changes.
For example the mechanism that supports a stack is same whether the stack is storing Integer,String, Object or Thread. With generics you can define the algorithm once,independently any specific type of data and then apply that algorithm to a wide verity of data types without any additional effort.
With generics:
-Explicit type cast is not needed because the compiler know which type of data is stored.
-Many kind of runtime mismatch errors can be avoided.
General form:
class class-name{//class declaration
//below creating reference
class-name var-name=new class-name(cons-arg-list);

No comments:

Post a Comment