Generics class Java

Generic classes/interfaces have the class name followed by a type parameter section. Type parameter section of can have one or more type parameters separated by commas. These classes/interfaces are known as parameterized classes/interfaces.

Example:

GenericsTest.java

/**
 * This class is used to show the use generics class.
 * @author w3schools
 */
class Test<T> {
	  private T item;
 
	  public Test(T item){
		  this.item = item;
	  }
 
	  public T getItem() {
		  return item;
	  }
 
	  public void setItem(T item) {
		this.item = item;
	  }	 
 
	  public void showItemDetails(){
		  System.out.println("Value of the item: " 
				  + item);
		  System.out.println("Type of the item: " 
				  + item.getClass().getName());
	  }
}
 
public class GenericsTest {	
	public static void main(String args[]){
		//String type test
		Test<String> test1 = 
			new Test<String>("Test String.");
		test1.showItemDetails();
 
		//Integer type test
		Test<Integer> test2 = 
			new Test<Integer>(100);
		test2.showItemDetails();		
	}
}

Output:

Value of the item: Test String.
Type of the item: java.lang.String
Value of the item: 100
Type of the item: java.lang.Integer

Download this example.
 

Generics class example with two parameters:

GenericsTest.java

/**
 * This class is used to show the use generics 
 * class with two parameters.
 * @author w3schools
 */
class Test<T, U> {
  private T itemT;
  private U itemU;
 
  public Test(T itemT, U itemU){
	  this.itemT = itemT;
	  this.itemU = itemU;
  }
 
  public T getItemT() {
	return itemT;
  }	
 
  public void setItemT(T itemT) {
	  this.itemT = itemT;
  }
 
  public U getItemU() {
	  return itemU;
  }
 
  public void setItemU(U itemU) {
	  this.itemU = itemU;
  }
 
  public void showItemDetails(){
	  System.out.println("Value of the itemT: " 
			  + itemT);
	  System.out.println("Type of the itemT: " 
			  + itemT.getClass().getName());
	  System.out.println("Value of the itemU: " 
			  + itemU);
	  System.out.println("Type of the itemU: " 
			  + itemU.getClass().getName());
  }
}
 
public class GenericsTest {	
	public static void main(String args[]){
		//String type test
		Test<String, Integer> test = 
		  new Test<String, Integer>("Test String.", 100);
		test.showItemDetails();
	}
}

Output:

Value of the itemT: Test String.
Type of the itemT: java.lang.String
Value of the itemU: 100
Type of the itemU: java.lang.Integer

Download this example.