Generic Classes in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sreekandank
    New Member
    • Jun 2009
    • 45

    Generic Classes in Java

    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>.

    Code:
    class Employee<T>
    {
     private T obj;
     Employee(T obj)
     {
      this.obj=obj;
     }
     T getObj()
     {
      return obj;
     }
    }
    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;
     }
    }
    /**
    *@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());
     }
    }
Working...