Javasoft has introduced generics data types as part of 1.5. This is one of the major items as part of this release.
Generic types or parameterized types
Writing classes,interfaces and methods in a type safe manner is called generic types. A generic class (or) a generic interface (or) a generic method can handle any type of data. Generic types are not act upon primitive data types.Syntax:
T meant for generic parameter.
//A generic class to store any type object
this.obj = obj;
public static void main(String args)
Myclass<Integer> obj = new Myclass<Integer>(i);
When we compile the above program, compiler generates a new generic version program by substituting Integer in place of T. We can use any data type in place of "T" i.e.; we can store a float value or a string value etc as below
Notes on generic data types
//store float obj
Float f = 15.5f;
Myclass<Float>obj = new Myclass<Float>(f);
//store string obj
String str = "Nalgonda";
Myclass<String> obj = new Myclass<String>(str);
- Writing classes, interfaces and methods in a type safe manner
- Generic types can handle any type of data.
- Generic types are declared as sub class types of Object class. So, they can act on any object.
- Generic types can't act on primitive types
- The compiler generates the non generic version of the class from its generic version using the specified data types. This is called "ensure"
- We can avoid type casting in many cases if we use generic types
- We can't create an object to generic type parameter (T i.e.; new T() is an invalid statement)