Suppose you have a generic class and you want that it will take only numbers i.e. integer, float,double. You can not put any other type in the type argument.
class Gen
{
T obj;
Gen(T a){this.obj=a;}
T getobj(){return obj;}
};
class demo
{
public static void main(String[] args){
Gen
System.out.println(i.getobj());
Double num=10.1;
Gen
System.out.println(d.getobj());
//Gen
}};
Here we can put only sub class of Number as type argument.
When we try to put String it becomes compilation error.
In addition to using class type as bound we can use interface also. You can specify multiple interfaces as bound. So a bound can include both a class type and one or more interfaces.In this case the class type must be specified first. When bound includes an interface type, only typearguments that implement that interface is legal.
class Gen
Here any type argument passed to ‘T’ must extend Myclass and implement Myinterface.
Wildcard arguments:
Suppose one wants to define a method inside generic class which compares the value of different type of generic class objects and returns the result irrespective of their type.
class Gen
{
T obj;
Gen(T a){this.obj=a;}
void equal(Gen o){//’?’ is wild card to make type valid for all
if(obj==o.obj)
System.out.println("TRUE");
else
System.out.println("FALSE");
}};
class demo
{
public static void main(String[] args){
Gen
Gen
Gen
i.equal(i1);
i.equal(str);
}};
In the above program wild card argument is used. represents the wild card argument and it will work irrespective of type.
See the argument passed in equal() is the type of Gen. but we can pass any value as the type argument of Gen. So we use wildcard argument which can take any type of argument.
Wildcards can also be bounded. Like this
Void equal(Gen o)
If we do like this in above program then we can not compare the ‘str’ instance. Otherwise compilation fails.
No comments:
Post a Comment