class A{
int a=10;
public void show(){
System.out.println("Show A: "+a);
}
}
class B extends A{
public int b=20;
public void show(){
System.out.println("Show B: "+b);
}
}
public class DynamicMethodDispatch {
public static void main(String[] args) {
A aObj = new A();
aObj.show(); //output - 10
B bObj = new B();
bObj.show(); //output - 20
aObj = bObj; //assigning the B obj to A..
aObj.show(); //output - 20
aObj = new B();
aObj.show(); //output - 20
System.out.println(bObj.b); //output - 20
//System.out.println(aObj.b); //It is giving error
}
}
In the above program i’m getting Error wen i try invoking aObj.b.
1.why i’m not able to acess that variable through the aObj though it is refering to class B??
2. why i’m able to acess the method show()?
You have to distinguish between the static type of
aObjand the runtime type ofaObj.Code such as
results in an
aObjvariable with static typeAand runtime typeB.The compiler will only bother too look at the static type when deciding what to allow or not.
To your questions:
Because there is (in general) no way for the compiler to know that
aObjwill refer to aBobject at runtime, only that it will refer to some form ofAobject. Since.bis not available on allAobjects, so the compiler will think “better safe than sorry” and disallow it.Because this method is available in all
Aobjects (if it’s not declared in the subclass, it is still inherited fromA).