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

10,746

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

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) :-)

Solution 5

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#.

Share:
10,746
jtht
Author by

jtht

Updated on June 12, 2022

Comments

  • jtht
    jtht about 2 years

    I have a parent class, A, and a child class, B, and B overrides a method, f, from A.

    public class A
    {
        public String f()
        {
            return "A";
        }
    }
    
    public class B extends A
    {
        ...
        public String f()
        {
            return "B";
        }
    
        public static void main(String[] args)
        {
            B b = new B();
            A a = (A) b;
            System.out.println(b.f()); //prints: B
        }
    }
    

    I create an object of type B, b, and cast that to type A and assign it to a variable of type A, a, and then call the method f on a. Now I'd expect the method of the parent class to be called since I'm working with an object of Type A but it doesn't, it calls the b version of the method(prints "B" instead of "A" in the code below).

    Why is it like this? Is it a design decision or a limit of technology?