0

I have Java 8 generics question .

I have following class hierarchy:

Employee is base class
Manager extends Employee
Executive extends Manager

The following line (1) does not compile:

(1) List<? super Manager> foos1 = new ArrayList<Executive>(); // error

The below lines 2 and 3 compile ok:

(2) List<? super Manager> foos2 = new ArrayList<Manager>();   
(3) List<? super Manager> foos3 = new ArrayList<Employee>();  

however, even though I can still add Executive like so:

(4) foos2.add(new Manager("Manager!",123));
(5) foos3.add(new Executive("Executive!",1.0,2));

Please explain the logic why I can not assign variable

<? super Manager> = ArrayList<Executive> 

where Executive is a super of Manager but I can still add Executive object to the array list?

many thanks!

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
Acid Rider
  • 1,557
  • 3
  • 17
  • 25

2 Answers2

4

Executive is a sub class of Manager, not a superclass.

The other two work because Employee is a superclass of Manager and type bounds are inclusive (i.e. the class itself or any of its superclasses), so Manager fits in the bounds.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • I'm betting the OP got confused because this is the opposite of the way the hierarchy works in business. Although of course the hierarchy in his code is the way things _should_ be ... (http://dilbert.com/strip/1994-01-04) – ajb Feb 18 '16 at 07:08
4
List<? super Manager> foos1 = new ArrayList<Executive>(); // error 

? super SomeClass
What this means is that you can create a new List of a class which is a Super-class of SomeClass. Since Executive is NOT a super-class of Manager, you can't assign List<? super Manager> foos1 = new ArrayList<Executive>();

Next, why foos3.add(new Executive("Executive!",1.0,2)); works?
Now, List<? super Manager> foos3 = new ArrayList<Employee>(); can accept any Manager instance. Turns out Executive is a Manager, so you can add an Executive to the List

TheLostMind
  • 35,966
  • 12
  • 68
  • 104