According to my understanding, a protected method can be accessed by any class within the same package, but only subclasses to this class can access from other packages .
package Parent;
public class Parent {
protected void display() {
//Code here
}
}
import Parent;
package Child;
class Child extends Parent{
void view(Parent p1) {
this.display(); // Success
p1.display(); // Error
}
void next(Parent p2) {
p2.foo(); //Success
}
}
Here this.display()
is successful because the child class is responsible for implementation. But p1.display()
does not work as p1
is not part of Child
class.
How can we justify this behaviour in the case of accessing protected methods from classes within the same package?