Wednesday, September 14, 2016

Generic Type Data in Java



So often we use Template class in C++ but Java too have Generic Data type.
Generic type data will accept any and all types for the type of arguments. Generic allows a function or class to work on many different data types without being rewritten for each one. Instead of writing multiple overloaded functions for the same purpose but with different data types we can use generic type and do the same with a single function.



Ex. 1


  class Numb<T>
    {

        T A,B;

        public Numb(T A,T B)
          {
              this.A = A;
              this.B = B;
          }
        void Disp()
          {
              System.out.print(A+"  "+B);
          }

        public static void main(String[] args)
          {
              Numb n1 = new Numb(10,20);
              Numb n2 = new Numb(10.5,20.5);
              Numb n3 = new Numb("First","Second");
              System.out.println("\nInteger : ");
              n1.Disp();
              System.out.println("\nDouble  : ");
              n2.Disp();
              System.out.println("\nString  : ");
              n3.Disp();
  
           }
    }


Output:


Integer :
10  20
Double  :
10.5  20.5
String  :
First  Second



Ex. 2


class MAX<T>
    {

        T A,B,C;
        public MAX(T A,T B)
          {
              this.A = A;
              this.B = B;
          }
        void Maximum()
          {
              System.out.print("A : "+A+"   B : "+B+" =  ");
              System.out.print(A.toString().compareTo(B.toString())>0?A:B);
          }

        public static void main(String[] args)
          {
              MAX m1 = new MAX(10,20);
              MAX m2 = new MAX(10.5,20.5);
              MAX m3 = new MAX("First","Second");
              System.out.println("\nInteger : Maximum of ");
              m1.Maximum();
              System.out.println("\nDouble : Maximum of ");
              m2.Maximum();
              System.out.println("\nString : Maximum of ");
              m3.Maximum();
          }
     }



Output:


Integer : Maximum of
A : 10   B : 20 =  20
Double : Maximum of
A : 10.5   B : 20.5 =  20.5
String : Maximum of
A : First   B : Second =  Second