Why a super keyword in generics is not allowed at the class level

At Generics

class A<T extends Number> allowed

But

class A<T super Integer> not allowed

I do not understand. It may sound like a newbie, but I'm stuck in it

+5
source share
2 answers

Quote from Java Generics: Extends, Super, and Wildcards :

Superclasses are not allowed in a class definition.

 //this code does not compile ! class Forbidden<X super Vehicle> { } 

Why? Because such a design does not make sense. For example, you cannot remove a type parameter using Vehicle because the Forbidden class can be created using Object. Thus, you should still erase parameters of type Object. If you think about the Forbidden class, it can take any value instead of X, and not just for Vehicle superclasses. It makes no sense to use super-binding, it will not bring us anything. Therefore, this is not permitted.

+4
source

Consider this example: -

Case 1 Upper bound:

 public class Node<T extends Comparable<T>> { private T data; private Node<T> next; } 

In this case, the erasure type replaces the associated parameter T with the first class of Comparable boundaries.

 public class Node { private Comparable data; private Node next; } 

As we know, a reference to a Parent class can be used to refer to an object of a child class . Thus, this code is acceptable since the data link may point to a Comparable instance or its child classes.

Case 2 Lower bound:

If we have code similar to

 public class Node<T super Comparable<T>> { private T data; private Node<T> next; } 

In this case, Compiler cannot use Object or any other class to replace the associated type T here, and it is also impossible that a reference to a child class can be used to refer to an instance of the parent class.

0
source

All Articles