Total Pageviews

Search This Blog

Tuesday, March 15, 2011

Generics in java

Lets learn how Generic works in java:
First let create a class Test4 which take a generic type, right now we dnt know anything about E. It will be decided at object creation time:

public class Test4 {
E param1;
Test4(){}

void setParam1(E param1){
this.param1 = param1;
}
E getParam1(){
return param1;
}


}


Now after developing Test4 class now use this class in our Manager4 class.
Lets create two instance of Test4 class one taking String type and other taking Integer type.

public class Manager4 {
@SuppressWarnings("unchecked")

public static void main(String[] args) {
Test4 t1 = new Test4();
Test4 t2= new Test4();
t1.setParam1("hello");
t2.setParam1(4000);

System.out.println(t1.getParam1());
System.out.println(t2.getParam1());

Test4 t3 = new Test4();
t3.setParam1("hello");
// String s2 = t3.getParam1(); //we hav to downcast it to String
String s2 = (String) t3.getParam1();
System.out.println(s2);
}

}

No comments:

Post a Comment