Why super keyword in generics is not allowed at class level

穿精又带淫゛_ 提交于 2019-12-30 03:09:45

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/37411256/why-super-keyword-in-generics-is-not-allowed-at-class-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!