Example of Generic class with one type parameter:

class Gen
{
T obj;//declare an object of type T
Gen(T a){this.obj=a;}
T getobj(){return obj;}
};
class demo
{
public static void main(String[] args){
Gen i=new Gen(10);
System.out.println(i.getobj());
Gen str=new Gen("bhabani");
System.out.println(str.getobj());
}};
Output:
10
Bhabani
Here ‘T’ is the type parameter. This name is used as a place holder for the actual type that will be passed to ‘Gen’ when object is created.
T obj; here declaration of an object of type T. if string is type parameter(T) then obj is String.
Gen str=new Gen("bhabani");
Here type parameter String is specified.
That means the String here replaces the ‘T’ in the ‘Gen’ class.

1 comment:

  1. This comment has been removed by the author.

    ReplyDelete