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.


Class classname<T>

T meant for generic parameter.

//A generic class to store any type object
class Myclass<T>
T obj;
Myclass(T obj)
this.obj = obj;
T getobj()
return obj;
class Gen
public static void main(String args[])
Integer i=50;
Myclass<Integer> obj = new Myclass<Integer>(i);
System.out.println("Value: "+obj.getobj());

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

//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);
Notes on generic data types
  1. Writing classes, interfaces and methods in a type safe manner
  2. Generic types can handle any type of data.
  3. Generic types are declared as sub class types of Object class. So, they can act on any object.
  4. Generic types can't act on primitive types
  5. The compiler generates the non generic version of the class from its generic version using the specified data types. This is called "ensure"
  6. We can avoid type casting in many cases if we use generic types
  7. We can't create an object to generic type parameter (T i.e.; new T() is an invalid statement)