Community
Participate
Working Groups
If a protected method is redefined in another package, the compiler signals an error when we try to call it on the subclass. If we just remove the redefinition, compilation is OK. Example (three classes hlb.err.Test, hlb.err.Root, hlb.err.other.Leaf): package hlb.err; public class Test { public Test() { super(); } public static void main( String[] args ) { hlb.err.other.Leaf leaf = new hlb.err.other.Leaf(); Root root = leaf; // This instruction compiles well. // Its execution calls the "protectedMethod1" of the Leaf // class, because "protectedMethod1" is redefined in Leaf. root.protectedMethod1(); // This instruction compiles well. // Its execution calls the "protectedMethod2" of the Root // class, because "protectedMethod2" is not redefined in Leaf. root.protectedMethod2(); // Here is the problem: this instruction doesn't compile. // I expected it to do exactly the same as // "root.protectedMethod1()". leaf.protectedMethod1(); // This instruction compiles well. // The only difference with the previous instruction is that // "protectedMethod2" is NOT redefined in Leaf. leaf.protectedMethod2(); // The fact that we have redefined "protectedMethod1" in Leaf // should not prevent from calling it, since it is defined and // accessible in Root. } } package hlb.err; public class Root { public Root() { super(); } protected void protectedMethod1() { System.out.println( "hlb.err.Root.protectedMethod1" ); } protected void protectedMethod2() { System.out.println( "hlb.err.Root.protectedMethod2" ); } } package hlb.err.other; public class Leaf extends hlb.err.Root { public Leaf() { super(); } protected void protectedMethod1() { System.out.println( "hlb.err.other.Leaf.protectedMethod1" ); } }
What are your compiler settings?
(In reply to comment #1) > What are your compiler settings? I use all the default settings, that comes when you just install the product. I use the 1.4.2_06 jdk from Sun. Its a little hard to "dump" all these settings here (is there an easy way to do that ?). But be sure I use all default values ...
Access to protected method across package boundaries is quite constrained. "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." Please refer for more details to JLS 6.6.2 and 6.6.7. Basically, the following would compile fine. You can perform access from other package only within code which is a subclass of target member declaring class and only if invoked to itself (this or implicit receiver). package hlb.err; public class Test extends hlb.err.other.Leaf { void foo() { this.protectedMethod1(); } }