DEV Community

loading...
Cover image for Generics in java

Generics in java

Shahed Abdulwahab
Updated on ・2 min read
You can have this dish prepared with any type of meat or fish.
-Entry on a restaurant menu.

Classes and methods can have Type parameter T, and the type parameter may then have any reference type or class type plugged in for the type parameter.

  • The class with type parameter is called Generic class or Parameterized class, example:
public class Sample<T> {
    private T data;  //T is a parameter for a type

    public Sample(T data) {
        this.data = data;
    }

    public T getData() {
        return data;
    }

}
Enter fullscreen mode Exit fullscreen mode
  • A generic constructor name has no type parameter with angular brackets with it's name, But it can use the type parameter T with it's parameters.
  • You can not plug in a primitive type for a type parameter, for example: if we want instantiate the generic class Sample with integer type, we would say:
Sample<Integer> sample = new Sample<>(55);
Enter fullscreen mode Exit fullscreen mode
  • A type parameter cannot be used everywhere a type name can be used. you can not use the type parameter T with new operator to create an object. example:
T object = new T (); //the first T is legal while the  second is illegal
Enter fullscreen mode Exit fullscreen mode
  • A generic class definition can have any number of type parameter, example:
public class Sample2<T1, T2> {

    private T1 data1;
    private T2 data2;
     .
     .
}
Enter fullscreen mode Exit fullscreen mode
  • A generic class can not be a an exception class, for example the following exception class will generate a compiler error:
public class Sample<T> extends Exception{} //illegal
Enter fullscreen mode Exit fullscreen mode

-To use compareTo method in your generic class, you need to ensure that the class implements comparable interface and begin with the following definition:

public class Sample <T extends Comparable>
Enter fullscreen mode Exit fullscreen mode

and the part extends Comparable is called bound on the type parameter T, and a bound may be a class name, for example the following says that only descendent classes of Employee may be plugged in for T:

public class Sample <T extends Employee>
Enter fullscreen mode Exit fullscreen mode

Generic Methods

  • the generic method can be member of a generic class or nongeneric class. ex:
public static <T> T getMidPoint(T[] a){
return a[a.length/2];
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)