INTRODUCTION OF GENERIC

Introduction Of Generic


Generic:-

  • Generics is one of the most important key feature in JDK1.5.

  • Though we are using Primitive data type as well as Derived data type, there is another data type i.e. Generic data type.

  • For Primitive data type we can assign corresponding primitive values.Even for Derived datatype also we can assign same derived object type(or)subclass type , But other derived type is not possible.

  • Incase of primitive and derived datatypes once if we define for any entity(or)class members i.e. methods(or)attributes it won’t change for entire life time of execution(data type)for any object(or)common to all object.

  • But if we use Generics(or)Generic data type we can able to define datatype while creating each object.

How to define Generic types for Class:

  • For Generic data type there are no specific keywords like Primitive or Derived at the time of defining but while using any one of the existing data type it must be specified or fixed at the time of object creation for that corresponding class.

  • Once we fix the data type for Generic data type while creating object it won’t change for the entire life time for the corresponding object.

Syntax for declaring Class type Generics:

    Syntax:

      class A(T)

      { -------

      ------- }

  • Here we can also use multi letters for specifying generic data type name.

  • Use single letter in upper case which is advisable.

  • But generic name should not start with Numeric and Special character.

  • Now we can call Class A as Generic class.

  • T acts as Generic data type for entire Class A.

  • Syntax:

      class (ABC)

      { -------

      ------- }

  • Class C is Generic Class and ABC will act as Generic datatype for Class C.

How to define in Generic Attribute:

    Syntax:

      class A(T)

      { T t1;

      T t2; }

  • Here t1,t2 are two attributes it’s type is generics.

Example 1:

 
            
              package com.sdj;
              class A<T>
              {
                T t1;
                T t2;
              }
              public class Generic
              {
                public static void main(String[] args) 
                {
                  A<integer> a1=new A();
                  a1.t1=newInteger("30");
                  a1.t2=newInteger("40");
                  A a2=new A();
                  a2.t1="abc";
                  a2.t2="123";
                  A<Integer> a3=new A<Integer>();
                  /* A<Integer> a4=new A<Float>(); */
              /* A<Number> a5=new A<Integer>(); */
                  A<Number> a6=new A<Number>();
                  a6.t1=newInteger("100");
                  a6.t1=newInteger("20");
                  a6.t2=new Float("20.30f");
                }
              } 
                  
  • Line no “10” we can’t use Primitive datatype we can use only Derived datatype.

  • Generic supports only Derived data type but not Primitive data type.

  • Line no “17”Here we passed same type of Derived type. so it is Not possible.

  • Line no “18” Here we passed same type of Derived type. so it is Not possible.

    Note
    • We can’t create Object to the Generic directly.
  • Line no” 3&4”:We can’t assign any specific value directly to the Generic type Attribute.

  • Line no 5 ;we can able to assign only null value because Null is a global to all Derived types.

  • Line no 6 :we can’t able to create Object to Generic type.

    Note
    • We can use Generic type for Constructor parameter also.

Example 2:

 
            
              package com.sdj.pack1;
              class A<;X>
              {
                X x;
                A(X x1)
                {
                  this.x=x1;
                }
                A()
                {

                }
                void setX(X x1)
                {
                  this.x=x1;
                }
                X getX()
                {
                  return x;
                }
              }
              public class GenericExp
              {
                public static void main(String[] args)
                {
                  A a1=new A();
                  a1.setX("abc");
                  a1.setX(new Integer("20"));
                  String s1=(String)a1.getX();
                  String s2=(String)a1.getX();
                  /* Integer i1=a1.getx(); */
                  Integer i2=(Integer)a1.getX();
                  System.out.println(i2);
                  a1.setX("abc");
                  String s3=(String)a1.getX();
                  A<String> a2=new A<String>();
                  /* a2.setX(new Integer(20)); */
                  a2.setX("abc");
                  a1.setX(new Float("20.30f"));
                  String s4=a2.getX();
                  A<Object> a3=new A<Object>();
                  a3.setX(new Integer("20"));
                  a3.setX("abc");
                  /* String s5=a3.getX(); */
                  String s6=(String)a3.getX();
                }
              } 
                  

Explanation:

  • Line no 11 :Here we can use Generic data type method parameter also.

  • Line no 23 :Here we can’t assign directly integer object type to string type if we want to assign explicitly we should do explicitly down casting i.e. string s1=(string)a1.getX() Compile is success & we get Run time Exception as Class Cast Exception.

  • At line no 31, a2 is Generic type here we can’t assign directly String type Object to Integer type object and X is also String type.

  • At line no 33 compile time error occurs because Here we are assigning to Float type.

  • At line no 34 ,a2 is String type so casting is not possible.

  • According to a2 .class A is declared as string Generic we can able to pass only String type values where we are using that generic type in class A , but by using a1 reference variable we can pass any type Object why because for a1 we are not specific type to Generic type while by default Object type is Generic type.

How to define Generic data type supports only some specific class:

Example 3:

 
            
              package com.sdj;
              class A<T extends Number>
              {
                T t1;
                void m1()
                {

                }
              }
              public class GenericExp
              {
                public static void main(String[] args)
                {
                  A<Number> a1=new A<Number>();
                  A<Integer> a2=new A<Integer>();
                }
              } 
        
  • In this program T supports only Number class or sub class to that class.

  • Inside m1( ) we should use either object class methods or number class methods i.e. same type or super type but we can’t use sub type methods i.e integer ,float,double….

  • At line no 13 we get compile time error because object is super class for number class so we can’t assign super class object to sub class object but we can assign sub class or same type.

  • At line no 14 compilation fails because string class is sub class to object class but not to number class.

    Note
    • Inside method we can use same class or super class members but we can’t able to access the sub class specific members.

    • Incase of object creation we can use either same class or sub class but we can’t use super class members.

How to define Generic data type which supports only user defined class:

  • In set interface it is also possible to add elements through addAll(collection c) method and Hashset(collection c) . The following example show

Example 4:

 
            
              package com.sdj;
              class A
              {
                void m1()
                {

                }
              }
              class B extends A
              {
                void m2()
                {

                }
              }
              class C <T extends A>
              {
                void m3()
                {

                }
              }
              class D <T extends B>
              {
                void m4()
                {

                }
                void m5()
                {

                }
              }
              public class GenricExp1
              {
                public static void main(String[] args)
                {
                  C <A> c1=new C<A>();
                  C <B> c2=new C<B>();
                  D <B> d1=new D<B>();
                }
              } 
                  
  • Inside class C Object is super type and m3 is same type or sub type.

  • Inside class D object is master of super type and m4 is super type and m5 is same type or sub type.

  • At line no 31 we are assigning same type of object.

  • At line no 32 we are assigning same type or sub type.

  • At line no 33 we are assigning same type.

How to define Generic types to Interface:

  • Declaration of Generic type for interface is same as class.

  • For class,while creating object we will specify datatype to Generic type but for Interface we will specify the specific data type while implementing the Interface to any sub class.

 
            
              interface I<T>
              {

              }
              class A<P> Implements I<Number>
              {

              } 
                  
  • Here p acts as an Object.

Is it possible to declare Generic attribute inside interface:

  • Incase of interface we can’t able to declare the Generic attributes , because inside interface evry attribute should be a public static final ,Even if we won’t keep during compilation compiler will keeps like below.Public static final T t1=null;

  • Static is not applicable for the generics types.

Example 5:

 
            
              interface I<T>
              {
                public abstract T m1();
                public abstract void m2();  
              }
              class B<T> implements A
              {
                public T m3()
                {

                }
                public void m4()
                {

                }
              }
              public class GenericExp2
              {
                public static void main(String[] args)
                {
                  B<Object> b1=new B<Object>();
                  B<Integer> b2=new B<Integer>();
                  B<String> b3=new B<String>();
                }
              } 
                  
  • In case of primitive it checks same type only.

  • In case of Derived type it checks same type or sub type.

Explanation:

  • In case of creating object to class B, we use object type but here we are using Number type in interface so we that can’t create object like this. why because implementing abstract methods. The method type should be same as abstract interface methods or sub type but we can access here number.

    Note
    • Sub class Generic type can be used as return type for interface method while overriding or else it implements that abstract method.

    • But we can’t use as a method parameter for the implemented method.

Example 6:

 
            
              package com.sdj;
              interface A<T>
              {
                public abstract T m1();
                public abstract void m2(T t1);
              }
              class B<H extends Number>implements A<Number>
              {
                public H m3()
                {

                }
                public void m4(H h1)
                {

                }
                public void m5(Number h1)
                {

                }
              } 
                   
                  
  • Here sub class Generic type should be same orit should be sub class to Generic type.

Example 7:

 
            
              package com.sdj;
              class A<T>
              {

              }
              class B<H extends Number>implements A<Number>
              {
                public H m1()
                {

                }
                public void m2(H h1)
                {

                }
                public void m3(Number h1)
                {

                }
              } 
     
  • Class Generic type should be same or else it should be sub class Interface Generic type.

Example 8:

 
            
              package com.sdj;
              interface I<M>
              {

              }
              class A<N extends Integer>implements I<Number>
              {

              }
              class B &<N extends Number>implements I<Integer>
              {
              } 
                  
  • At line no 8 we get compile time error because class Generic type should be same or else it should be sub class Interface Generic type but here it is vice versa.

How to use Generic to only methods:

  • If we want to specificly define methods we can keep Generic type before to the method return type.

  • By using method Generic type we can specify the method while calling by passing specific datatype value.

Example 9:

 
            
              package com.sdj;
              class A
              {
                <T>void m1(T t1)
                {

                }
              }
              public class GenericExp2
              {
                public static void main(String[] args)
                {
                  A a1=new A();
                  a1.m1(new Integer("20"));
                  String s1="abc";
                  a1.m1(s1);
                  a1.m1(20);
                  float f1=new float("20.25f");
                  a1.m1(f1);
                }
              } 
                  
  • Through method Generic data type we can avoid usage of method overloading concept.

How to use multiple Generics:

    We can use ‘N’ Number of generics.

Example 10:

 
            
              package com.sdj;
              class A<T,E>
              {
                T t1;
                E e1;
                void m1(T t1, E e1)
                {

                }
              }
              public class Genericjava
              {
                public static void main(String[] args)
                {
                  A<String,Integer> a1=new A<String,Integer>();
                  a1m1("Sudha",new Integer("23"));
                  /* a1.m1(new Integer("20"),"Guna"); */
                  A a2=new A<Integer,String>();
                  a2.m1(new Integer("23"),new String("sudha"));
                  /* a2.m1("Uday"),new Integer("30")); */
                }
              }