Protected members access from different packages in Java – a curiosity
package packageOne;
package packageOne; public class Base { protected void display(){ system.out.println("in Base"); } } package packageTwo; public class Derived extends packageOne.Base{ public void show(){ new Base().display();//this is not working throws compilation error that display() from the type Base is not visible new Derived().display();//is working display();//is working } }
The two packages are in two different files But why?
Solution
http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6
class C protected member; // in a different package class S extends C obj.member; // only allowed if type of obj is S or subclass of S
The motives may be as follows If obj is s, s class has enough internal knowledge, it has the right to manipulate its members, and can perform this operation safely
If obj is not s, it may be another subclass S2 of C. s does not know S2 may not have been born when s was written It is quite dangerous for s to manipulate the protected internal components of S2 If this is allowed, from the perspective of S2, it does not know who will tamper with its protected internal parts and how, which makes S2 work very difficult to infer its own state
Now, if obj is D, D extends S. is it dangerous for s to access obj member? It's not true S using members are the shared knowledge of S and all its subclasses, including D. s as a superclass has the right to define behavior, and D as a subclass has the obligation to accept and abide by it
For easier understanding, the rules should be simplified so that the obj (static) type is completely S. after all, subclass D is very unusual and inappropriate in S Even if the static type of obj is D, our simplification rule can be easily handled by uploading: ((s) obj) member