InterviewSolution
| 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> { MyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>(); 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> { MyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>(); |
|