6

i've got the class P4 in the default package (i know using the default package is bad practice, but merely "for example" for now):

import temp.P2;

public class P4 extends P2 {

public void someMethod() {    
    P2 p2 = new P2();
//        p2.p2default();   // ERROR as expected
    p2.p2public();
    p2.p2protected();  // ERROR as not expected
}    

}

and class P2 in package temp

package temp;

public class P2 {

protected void p2protected() {    
...
}    

public void p2public() {    
...
}    

void p2default() {    
...
}    

}

From the access control mechanism, i'd expect P4-- having extended P2, should be able to see the protected member of its super class even from outside the package once it imported the namespace of that package.

What am i missing?

TIA.

0

3 Answers 3

4

The issue may be that you are not trying to inherit the p2protected() method, which you should be able to do, but rather to call p2protected(). You cannot call a protected method on a different object from a different package, even if you are extending the class. super.p2protected() should work, however.

1
  • thx - yours & @manouti's explain all&well. his is more direct. you get the upvote & he the accept. Aug 18, 2014 at 18:30
2

You defined P2 p2 = new P2(); of type P2 and not P4. If p2 were of type P4 it would have access to it since it is a subclass of P2.

1

From the JLS :

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.

In your code you are trying to access the protected member of another object.

public void someMethod() {    
    P2 p2 = new P2();

    p2.p2protected();  // doesn't work, because someMethod and p2.p2protected
                       // operate on different objects (this vs. p2) 

    p2protected (); // works, because someMethod and p2protected operate
                    // on the same object (this)
} 

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.