Friday, January 17, 2020

Generics Types

Generic Type Constructor

we can create generic type constructors of generic classes. We can see in the following example, there is a Generic class Block with a Constructor. We can create objects of specific type when we need. 

class Block<T> // Generic class(Type)
{  
T h,w,l; // field Declaration
public Block(T h, T w, T l) {// Generic type constructor
       super();
       this.h = h;
       this.w = w;
       this.l = l;   
}
}
public class GenConstructorDemo {

    public static void main(String[] args) {
       Block<Integer> b1= new Block<Integer>(4,7,9);    //object-1
       Block<Float> b2=new Block<Float>(12.3f,7.6f,9.7f);//Object-2
       Block<Long> b3=new Block<Long>(5000L,7000L,9000L);//Object -3
      }
    }


Generic Methods

Generic methods are much similar to generic classes. They are different only in one aspect that scope of type information is inside method (or constructor) only. Generic methods are methods that introduce their own type parameters.


/******************************************************/
class Rectangle<T> // Generic Class or Type Rectangle
{
    private T h;
    private T w;
    public Rectangle(T h, T w) {
       super();
       this.h = h;
       this.w = w;
    }
    }

    public T getH() {  // Getter and setter Methods
       return h;
    }
    public void setH(T h) {
       this.h = h;
    }
    public T getW() {
       return w;
    }
    public void setW(T w) {
       this.w = w;
    }

}
class Util  // Utility Class
{

    public static <T> void displayRectangle(Rectangle r)
    {
       System.out.println("h="+r.getH()+" w="+ r.getW());
    }
}
public class GenericsDemo {//Main Class

    public static void main(String[] args) {
    Rectangle<Integer> rint=new Rectangle<Integer>(12,20);
    Rectangle<Float> rfloat=new Rectangle<Float>(30.6f,23.5f);
    Util.<Integer>displayRectangle(rint);
    Util.<Float>displayRectangle(rfloat);
    }
}

Generic Type Array 

We can create generic type arrays like following example. We can not initialize generic type array.


public class GenArrDemo<T>{
 T[] t1; //it will work
 T[] t2=new T[10];// it will not work
                  //Compile time error

}


Video Tutorial