CodesJava

Easy learning with example program codes

Generics constructor

Generics constructor in java example:

A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface. The interface constructor is generic.

Example:

GenericsTest.java

/**
 * This class is used to show the use of generics constructor.
 * @author codesjava
 */
class Test {
	//Generics constructor
	public <T> Test(T item){
		 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 test1 = new Test("Test String.");
		Test test2 = new Test(100);
	}
}

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.
 
Next Topic: Generics constructor example with two parameters.
Previous Topic: Generics method example with two parameters.

 

Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status