Java Generic

Generic are resolve the dependency of data type in our source program. In other word generics type of object is capable to working on any data value. Java is an one of the programming language which are strongly check the data type of every variables. Compiler is not compile the source code, when variables are assigned invalid data type of values. Generic class and method are provide the solution of this problem. That is enabling to working on same type of operation different data type values.

Generic Method

Suppose we are need to a method which are add two primitive data type values. In generic method are is one of the best solution of this problem. We need to define only one generic variant of method that are solve this problem.

class Demo 
{ 
    // Method which are accept generic parameter
    public <T> void dataRecord (T data) 
    { 
      //Display pass data class and its values
        System.out.println(data.getClass().getName() + " = " + data); 
    } 
   
    public static void main(String[] args) 
    { 
      Demo t = new Demo();
         
        t.dataRecord("Code");  //Passing the String value
   
        t.dataRecord(true); //Passing the boolean value
   
        t.dataRecord(4.0); //Passing the double data value

        t.dataRecord(12); //Passing the integer data value
    } 
}
java.lang.String = Code
java.lang.Boolean = true
java.lang.Double = 4.0
java.lang.Integer = 12

Generic Class

//Single variant generic class
//<T> is generic data type
class GenericOne<T>{
  
}
//Double variant generic data type
//<T,U> is generic data type
class GenericTwo<T,U>{
  
}
class DataCollect<T>{
    //instance variable
    public T record; //gneric object

    public DataCollect(T record){

      this.record=record;

    }
    public T getRecord(){
      return record;
    }

    
    public static void main(String[] args) 
    { 
      DataCollect<String> first = new DataCollect<String>("XYZ");

      DataCollect<Integer> second = new DataCollect<Integer>(10);

      DataCollect<Float>third = new DataCollect<Float>(5.5f);

      System.out.println(first.record);
      System.out.println(second.record);
      System.out.println(third.record);
   }
}
Generic class example
XYZ
10
5.5


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved