Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why super keyword in generics is not allowed at class level

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

like image 668
bananas Avatar asked May 24 '16 10:05

bananas


2 Answers

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.

like image 63
Andy Turner Avatar answered Nov 16 '22 20:11

Andy Turner


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.

like image 26
Vicky Avatar answered Nov 16 '22 22:11

Vicky