I feel like you're still slightly confused with why protected m1() isn't visible.
You understand that main is a method in B and B is a subclass of A, therefore you feel like it should be accessible.
The key is obj is cast to be interpreted of type A. Then you try to call instance method m1 from static context in B (see this link above for why this is important). By class A definition, m1 is accessible through:
- Class definition itself on a given instance of itself.
//example
package pkg1;
public class C {
protected void m1() {
System.out.println("protected method");
}
public static void callM1(C anInstanceOfC){
anInstanceOfC.m1();
}
}
package pkg2;
import pkg1.C;
public class D extends C {
@Override
public void m1() {
System.out.println("override m1");
}
public static void main(String ar[]) {
C obj=new D();
C.callM1(obj);//output would be "override m1"
}
}
- Instance methods (of course) of the class within itself and of subclasses.
//example
package pkg1;
public class C {
protected void m1() {
System.out.println("protected method");
}
public void m2() {
m1();//call to instance method m1
}
public static void callM1(C anInstanceOfC){
anInstanceOfC.m2();
}
}
package pkg2;
import pkg1.C;
public class D extends C {
@Override
public void m1() {
System.out.println("override m1");
}
public void m3() {
//super.m2()
m2();//call to superclass method
}
public static void main(String ar[]) {
D obj=new D();
D.m3(); // output "override m1"
}
}