In both super class A and sub class B i have variable abc as 10 and 20 respectively, and a method callme(), overrided in sub class.
If i do
A a = new B();
B b = B(new A());
then if i write
a.callme() -> calls B's method
b.callme() -> calls A's method.
This is because method is called based upon the actual object.
If i do
str = a.abc; // will print 10 , based upon ref var type A
str = b.abc; // will print 20 , based upon ref var type B
Why is this difference? Why not both method and variables accesses based upon the actual object?
Thanks
Remember, instance variables are never overidden, they are hidden. It is the type of reference that decides that whose instance variables will be accessed.
In subclass, the method
callme()is overidden. So, according to Dynamic method dispatch mechanism, it is the type of object that decides which method will be called at Runtime. It is because, objects are created at runtime.E.g