What is Generic Class


Generic class is a class which has been developed for a generic type, and this class can be used with any specific type.This specific type need to be specified to instantiate the class.

Java Compiler generates code, based on the specific type used during instantiation.

Generic classes cannot be used with primitive data types.

Below is an example of Generic class. In this example Wrapper is Generic class.

//Generic Class
class Abc{

}

class Wrapper {

  private K m;

  public void put(K m) {
    this.m = m;
  }

  public K get() {
	  System.out.println("in get()");
    return m;
  }
}


public class Box
{
  public static void main(String[] args) {
     Wrapper integerBox = new Wrapper();
     Wrapper stringBox = new Wrapper();
     Wrapper abcBox = new Wrapper();

     //Generic class doesn't work for primitive data types
     //Wrapper iBox = new Wrapper();

     integerBox.put(new Integer(10));
     stringBox.put(new String("Hello Java652.com"));

     System.out.println("Integer Value is "+ integerBox.get());
     System.out.println("String Value is "+ stringBox.get());

     Abc tmp = abcBox.get();
     System.out.println("Abc value :"+tmp.toString());
  }
}


You may also like to read: Inheriting from Generic Class
Store objects in Generic HashSet

2 thoughts on “What is Generic Class”

Leave a Reply