Java Reference
In-Depth Information
public void merge(PriorityQueue q) {
Cell first = q.head;
// ...
}
We are not accessing the protected member of the current object, but
the protected member of an object passed as an argument. This is al-
lowed because the class attempting the access is PriorityQueue and the
type of the reference q is also PriorityQueue . If q were a subclass of Pri-
orityQueue this access would also be valid.
Later the group determines that there is a new requirement: It wants to
be able to merge a SingleLinkQueue with a PriorityQueue . So it defines an
overloaded version of merge that starts like this:
public void merge(SingleLinkQueue q) {
Cell first = q.head;
// ...
}
But this code won't compile.
The problem is that the class attempting to access the protected member
is PriorityQueue while the type of the reference to the object being
accessed is SingleLinkQueue . SingleLinkQueue is not the same as, nor a
subclass of, PriorityQueue , so the access is not allowed. Although each
PriorityQueue is a SingleLinkQueue , not every SingleLinkQueue is a Prior-
ityQueue .
The reasoning behind the restriction is this: Each subclass inherits the
contract of the superclass and expands that contract in some way. Sup-
pose that one subclass, as part of its expanded contract, places con-
straints on the values of protected members of the superclass. If a dif-
ferent subclass could access the protected members of objects of the
 
Search WWH ::




Custom Search