I have two classes in two different packages:
package package1;
public class ParentClass {
public void testPublic() {
}
protected void testProtected() {
}
}
package package2;
import package1.ParentClass;
public class ChildClass extends ParentClass {
void test() {
ParentClass par = new ParentClass();
par.testProtected(); // Line 1 : ERROR: testProtected() has protected access in ParentClass
testProtected(); // Line 2 : No error
ChildClass ch = new ChildClass();
ch.testProtected(); // Line 3 : No ERROR
testProtected(); // Line 4 : No error
}
}
I am able to understand why there is NO ERROR in calling testProtected() -- Line 2
since ChildClass
sees this method as it inherits from ParentClass
.
And somehow able to understand why it is throwing ERROR in calling par.testProtected() -- Line 1
, since par
is a different object, and current object is not having access to other object's parent's protected method.
But how it is possible for an object of ChildClass to access this same method ch.testProtected() -- Line 3
(other object's parent's protected method) when the reference type is of ChildClass only?