Generic class is a class with one or more type variables. A Generic class declaration looks like a non-generic class declaration, except that the class name followed by a type parameter. For instance, consider a following generic class Employee<T>.
The Employee class introduces a Type variable T, enclosed in angle brackets <>, after the class name. The type variables can be used throughout the class definition to specify method return types, and the types of variables.
A generic class can have more than one type variables. For example,
class Employee<T,U>
Let's consider the following example program that shows the generic Employee class, and it uses the Type variable T.
Code:
class Employee<T>
{
private T obj;
Employee(T obj)
{
this.obj=obj;
}
T getObj()
{
return obj;
}
}
A generic class can have more than one type variables. For example,
class Employee<T,U>
Let's consider the following example program that shows the generic Employee class, and it uses the Type variable T.
Code:
class Employee<T>
{
private T obj;
Employee(T obj)
{
this.obj=obj;
}
T getObj()
{
return obj;
}
}
/**
*@author Sreekandan.K
*/
public class GenericEmployeeClass
{
public static void main(String args[])
{
Employee<String> str=new Employee<String>("AAS");
System.out.println("Name:"+str.getObj());
Employee<Integer> i=new Employee<Integer>(21);
System.out.println("Age:"+i.getObj());
Employee<Double> d=new Employee<Double>(30000.0);
System.out.println("Salary:"+d.getObj());
}
}