I am reading Core Java volume-1 by Horstmann, Cay.S
on generics
. I am not able to understand some explanation of the text book. I give the sample code below which the author refers to. followed by the text from the book and my question.
class Employees{ }
class Manager extends Employees { }
class Pair<T>{
private T first;
private T second;
Pair(T first, T second){
this.first=first;
this.second=second;
}
void setFirst(T value){
first=value;
}
T getFirst(){
return first;
}
}
public class WildCardGenerics {
public static void main(String[] args){
Manager ceo = new Manager();
Manager cfo=new Manager();
Employees clerk = new Employees();
Pair<Manager> managers= new Pair<>(ceo,cfo);
Pair<? extends Employees> employees=managers;
employees.setFirst(clerk);
}
}
From the book:
"""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:
? extends Employee getFirst()
void setFirst(? extends Employee)
This makes it impossible to call the setFirst
method. The compiler
only knows that it needs some subtype
of Employees
, but it doesn't know which type. It refuses to pass any specific type
- after all
?
might not match it."""
Question:
I do not understand why it refuses to pass any specific type. so what does this method accept?
? extends Employee
-- means include Employee and any subtype of Employee. so passing an Employee should be legal correct?
From the book:
pair<? super Manager> has methods:
void setFirst(? super Manager)
? super Manager getFirst()
The compiler doesnt' know the exact type of the setFirst
method and therefore can't call it
with an object of type Employee or Object
, but only with Manager
or a subtype
such as executive
.
Question: So here I say the method can accept any Manager objects or that extends Manager object (similar to subytpe bound above). Not clear to me as why?
From the book:
Intuitively speaking, wildcards with supertype bounds let you write to a generic object, while
wildcards with subtype bounds let you read from a generic object.
Question: I cannot follow it at all. It sounds simple,but not following the logic as what is meant.