1.

How Can We Restrict Generics To A Subclass Of Particular Class?

Answer»

In MyListGeneric, Type T is defined as PART of class declaration. Any Java Type can be used a type for this class. If we would want to RESTRICT the types allowed for a Generic Type, we can use a Generic Restrictions. Consider the EXAMPLE class below: In declaration of the class, we specified a constraint "T extends Number". We can use the class MyListRestricted with any class extending (any sub class of) Number - Float, Integer, Double etc.

class MyListRestricted<T extends Number> {
private List<T> values;
void add(T value) {
values.add(value);
}
void remove(T value) {
values.remove(value);
}
T get(int INDEX) {
return values.get(index);
}
}










MyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>();
restrictedListInteger.add(1);
restrictedListInteger.add(2);
String not valid substitute for constraint "T extends Number".
//MyListRestricted<String> restrictedStringList = 
// new MyListRestricted<String>();//COMPILER ERROR




In MyListGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions. Consider the example class below: In declaration of the class, we specified a constraint "T extends Number". We can use the class MyListRestricted with any class extending (any sub class of) Number - Float, Integer, Double etc.

class MyListRestricted<T extends Number> {
private List<T> values;
void add(T value) {
values.add(value);
}
void remove(T value) {
values.remove(value);
}
T get(int index) {
return values.get(index);
}
}










MyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>();
restrictedListInteger.add(1);
restrictedListInteger.add(2);
String not valid substitute for constraint "T extends Number".
//MyListRestricted<String> restrictedStringList = 
// new MyListRestricted<String>();//COMPILER ERROR






Discussion

No Comment Found