Bounded Type Parameter
- Eclipse: Oxygen
- Java: 1.8
There could be a situation where we need the user to enter a specific type of quantity. For such cases we use generics. For example, a method that accepts only String must not be passed with numbers and, therefore, bounded type parameters are used for such purposes.
In bounded type parameter, we are bounding or restricting to specific information.
In the following code, a restriction is applied to the parameter to pass the only number as an argument. To apply restriction types of display method extends the respective classes Like <E extends Character, N extends Number>
Now passing the value other than character and number is not possible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class Data<K extends Integer,V extends App> { private K key; private V value; public Data(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "Data [key=" + key + ", value=" + value + "]"; } public K getKey() { return key; } public V getValue() { return value; } public <E extends Character,N extends Number> void display(E element, N number){ System.out.println("Element: "+element+" Number: "+number); } } public class App { public static void main(String[] args) { Data<Integer,String> data = new Data<Integer,String>(1, “value” ); data.display('$', 1); } } |
Output
1 |
Element: $ Number: 1 |
In the following code, rule based on custom class is applied on the custom type parameter of Data class.
class Data<K extends Integer,V extends App>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class Data<K extends Integer,V extends App> { private K key; private V value; public Data(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "Data [key=" + key + ", value=" + value + "]"; } public K getKey() { return key; } public V getValue() { return value; } public <E extends Character,N extends Number> void display(E element, N number){ System.out.println("Element: "+element+" Number: "+number); } } public class App { public static void main(String[] args) { Data<Integer,App> data = new Data<Integer,App>(1, new App()); data.display('$', 1); data.getValue().test(); System.out.println(data.getKey()); } public void test(){ System.out.println("Testing...."); } } |
Output
1 2 3 4 5 |
Element: $ Number: 1 Testing.... 1 |
Contributed by: Poonam Tomar