Bounded Type Parameters
In this section, you will learn how we can bound the type parameter.
We can bound the types which are permitted to be passed to type parameter section. For example, we can create a method that operates only on number or its subclasses like Integer, Float etc.
Restricting type parameters section is known as Bounded Type Parameters.
You can declare bounded type parameter as follows :
public class AnimalActions<A extends Animal>
"A extends Animal" means whatever type we pass for the substitution of type parameter must extend/implement the Animal class/interface.
Here we can use only extends for both classes as well as for interface. Given below declaration is not valid :
public class AnimalActions<A implements Animal>
Given below the complete example :
Example :
public class BoundedTypeParamDemo<A> { private A a; public void set(A a) { this.a = a; } public A get() { return a; } public <U extends Number> void inspect(U u) { System.out.println("T: " + a.getClass().getName()); System.out.println("U: " + a.getClass().getName()); } public static void main(String[] args) { BoundedTypeParamDemo<Integer> integerBox = new BoundedTypeParamDemo<Integer>(); integerBox.set(new Integer(10)); integerBox.inspect(10); // The below line will give error integerBox.inspect("some text"); } }
Output :
The above code will give error because the generic method inspect(U u) is not applicable for the arguments of String type. The String type is not a valid substitute for the bounded parameter <U extends Number> :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Bound mismatch: The generic method inspect(U) of type BoundedTypeParamDemo<A> is not applicable for the arguments (String). The inferred type String is not a valid substitute for the bounded parameter <U extends Number> at BoundedTypeParamDemo.main(BoundedTypeParamDemo.java:25) |