Overriding methods in java and then casting object to parent class behavior

This is basis of polymorphism

And it is supposed to work like that.

Any method is dispatched (selected/invoked) dynamically according to the actual type of the object in stead of the type by which it is being referred to.

When you cast the object to another type, you just refer it using another type. The actual type of the object is not changed. (And it can never change).

So the behavior that you are observing is as expected and it is designed to be that way. It's definitely not a limitation.

Hope this helps.


It's a design decision. You've created an object of type "B", so that's what it is.

When you cast it to A, you're only telling the interpreter that the methods expected to be found in a class of type A are available for B, but since you have an @Override method for B, it's going to use it.


A a = (A) b;

By casting the variable a the reference hasnt changed so the method f is still invoked since method calls are polymorphic


When you cast the instance you are simply implying that it could be an instance from the super class, BUT the internal implementation of that instance will not change, that's why you get that result!

Metaphorically speaking, if you applied an american's person mask on an UK person (cast), that person would still be english (inheritance), but if you asked that person to speak (calling a method) you would still hear the british accent, not the american one (internal implementation is what matters in the end) :-)


This is how it's supposed to work. It's calling the method on B because that's how the variable was instantiated as. The type of the variable it was assigned to does not change the fact that a is actually of type B. Most languages are like this, including C#.