Monday 10 January 2022

Generics in Java

Generics means parameterised types. With the help of parameterised types we can create classes, interfaces or methods in such a way that the type of the data on which they operate can be passed as a parameter.

Generic only works with object. 

Main advantage of generic

  a)Generic provide Type Safety :: This means that error can be detected during compile time only instead of runtime .

  b)Generic provide Code Reusability :: Since with generic we just need to create class once and we can use it for any type .

 c)Type casting is not needed.

 d)Helpful for making generic implementation.

 Generic class creation: It is very similar to normal class except that the declaration is followed by type parameter with diamond bracket.

     Class Dao<T>{//T is generic type parameter

      private  T t; //instance of generic type

      } 

     

   Class Matrix<T,S>{

     private T t;

     private S r;

      }


By convention ,type parameter are named as single uppercase letter. Commonly used Type parameter are:

      * T    :   First typed parameter

      * S.   :   Second type parameter

      * U   :   Third type parameter

      * V   :   Fourth type parameter

      * K   :   Key type parameter


Bounded Type:: 

        Bounded type is used to restrict type to a specific type or its subtype. In short in many cases we want the type to be restricted to specific types like  in case of sum we want that type should be restricted to Number or its type then in that scenario we can use Bounded type.


Bounded types are divided on 3 types based on wildcard:

1)Upper Bound Type :: This is implemented using ?(unknown type) wildcard followed by extends keyword and used to relax the restriction on any type which means we can pass any type which extends Type T.

     public void  addNumsDifferentTypes(List<? extends Number> list>{

}


2)Lower Bounded Type :: This is implemented using ? (unknown type) followed by super keyword and used to allow specific type passed in parameters. This means we can pass only pass or return type of specific type or it super type while using it. 


     public void passOnlyIntegerOrNumber(List<? super  Integer> list){}


3)Unbounded Type:: This is implemented using ? (unknown type) and is used to allow pass or return any type.

    public void printList(List <?> list){}



No comments:

Post a Comment