In Generics
class A<T extends Number>
is allowed
But
class A<T super Integer>
is not allowed
I'm not getting this point. This may sound like novice question but I'm stuck in it
Quoting Java Generics: extends, super and wildcards explained:
The super bound is not allowed in class definition.
//this code does not compile ! class Forbidden<X super Vehicle> { }
Why? Because such construction doesn't make sense. For example, you can't erase the type parameter with Vehicle because the class Forbidden could be instantiated with Object. So you have to erase type parameters to Object anyway. If think about class Forbidden, it can take any value in place of X, not only superclasses of Vehicle. There's no point in using super bound, it wouldn't get us anything. Thus it is not allowed.
Consider this example:-
Case 1 Upper Bound:
public class Node<T extends Comparable<T>> {
private T data;
private Node<T> next;
}
In this case, type erasure replaces the bound parameter T
with the first bound class Comparable
.
public class Node {
private Comparable data;
private Node next;
}
As we know the fact Parent class reference can be used to refer to a child class object.So this code is acceptable in anyhow, as the reference data
can point to the instance of either Comparable
or its child classes.
Case 2 Lower Bound:
If we can have code something like
public class Node<T super Comparable<T>> {
private T data;
private Node<T> next;
}
In this case, Compiler can neither use Object
or any other class to replace bound type T
here and it is also not possible that a child class reference can be used to refer a parent class instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With