]A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
But, this is the same as:
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
protected members of a class are accessible by classes in the same package AND by it's subclasses unless the package.
Supposing that X is outside of the Y's package: even if X is not a subclass of Y, it still cannot access the protected members of Y. So I don't see something new in here?
That means, plain and simple, that class X can't access the protected members of an instance of class Y just because X is a subclass of Y. Your expectation about what ought to work is simply not right.
This is called inheritance and it is nothing more than logical.
On the other hand, if class Z is in turn a subclass of X, then the protected members declared in Y can be accessed in instances of Z by code in X. Got that?
This is true. I also have stated it in my first post in this topic:
Originally posted by Ernest Friedman-Hill:
It's the third and fourth lines that the original poster is asking about, and that is not captured by the sentence I've quoted above. It's this subtle issue that surprises people.
In the SubClass at "line 2" you creates a new instance of SuperClass (so you are not extending/subclassing it!), but it's protected members aren't visible, just because the class is in another package.
this is interesting stuff to think about
As for your last point about my last statement being a logical result of inheritance: yes, it is. But given the point discussed above, it's important to remember that sometimes logical deductions about inheritance can fail. For example, given these same classes, it is true that X and Z will both extend Y , but...
I will suppress my every urge. But not this shameless plug:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koophttps://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton