• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Can we use wildcards to corrupt a Pair<Manager> through a Pair<? extends Employee> reference


No corruption is possible. The call to setFirst is a type error. To see why, let us have a
closer look at the type Pair<? extends Employee>. Its methods look like this:
"

Core Java Vol. I (8th Edition). P.633

Why do I get a compile time error when I run wildcardBuddiges.setFirst to lowlyEmployee? What do you think the author referred to as lowlyEmployee?


 
Stephan van Hulst
Bartender
Posts: 6337
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Presumably, lowlyEmployee is an instance of Employee or a subclass of Employee, but not an instance of Manager.

It gives an error because you're not allowed to add just *any* kind of Employee to a Pair that *could be* a Pair of Managers (as it is, in this case).

Pair<? extends Employee> means, "A pair of something that extends Employee, but I don't know what! It could be a Pair<Employee>, or a Pair<Manager>, or even some other kind of Employee I don't know about".
 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:Presumably, lowlyEmployee is an instance of Employee or a subclass of Employee, but not an instance of Manager.

It gives an error because you're not allowed to add just *any* kind of Employee to a Pair that *could be* a Pair of Managers (as it is, in this case).

Pair<? extends Employee> means, "A pair of something that extends Employee, but I don't know what! It could be a Pair<Employee>, or a Pair<Manager>, or even some other kind of Employee I don't know about".


Hence, if lowlyEmployee is an Employee, why would the compiler complain?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your Pair class is defined in such a way that both the objects that you store in the pair must be of the exact same class.

When you have a Pair<? extends Employee> then the compiler cannot check that when you set values in the pair, they are indeed of the same class. You could call setFirst() with a Manager and setSecond() with an Employee, and then there would be a problem because Manager and Employee are two different classes. So to make sure you cannot do this the compiler simply gives an error if you try.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic