Tej Kumar Ch wrote:With the above I am expecting to invoke the Super class method and to print "A", But not happening.Its always calling the polymorphic method in B only.
Is there way to invoke that?
Your understanding is wrong!
You have to remember 1 very important rule: Which instance methods you can call/invoke is determined at compile time based on the reference variable type. Which instance method is actually executed is decided at runtime based on the type of the actual object (=
polymorphism). That's really a very, very important rule!
Now we go back to your example:
So if we apply the aforementioned rule to this code:
1/ the type of reference variable
x is
A => all methods defined in class
A can be invoked
2/ the type of the actual object reference variable
x is referring to, is
B => the method
mA in
B (which overrides method
mA in
A) will be executed (printing
In Mb).
3/ the type of reference variable
x is
A, the code on
line1 doesn't make any difference and is completely equivalent to the code on
line2. Because you cast, you are temporarely changing the type of the reference variable to
A (but it was already
A, so it doesn't make any difference). You do
not change the type of the actual object the reference variable is referring to (which is required to execute another method)
So which options do you have to execute method
mA in
A?
1/ Make sure the actual object the reference variable is referring to is of type
A
2/ In the overridden method you can invoke the base class version of the method using the
super keyword. So change the code of method
mA in
B to
Now the code
prints
A
In Mb
Hope it helps!
Kind regards,
Roel