I have been doing the exercises in Thinking In
Java and came across this one. Can anyone please explain this to me :
package p1;
public class A{// A is in package p1
protected void a(){
System.out.println("Hello");
}
}
package p2;
import p1.*;
public class B extends A{ // B is a sub class of A in another
// package p2
public static void main(
String args[]){
A a1=new A();
a1.a();
}
}
The compiler gives me an error message : a() has protected access in class A.
Changing the code in class B to:
A a1=new B() ---> also does not help. Compiler gives the same error message.
The code compiled and ran only when I changed the code :
B a1=new B();
My question is :
As per the defenition of protected, another package subclass can invoke a protected method in its superclass. B is a subclass of A in package p2. Why is it not able to access a() when I had written :
A a1=new A();
a1.a();
OR when I had written :
A a1=new B(); // trying late binding (dynamic method invocation)
a1.a();
Can anybody clarify this to me.
Thank you,
SJ