Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 693
jtht Avatar asked Apr 04 '14 23:04

jtht


People also ask

How you would call a parent class of an overriding method in a child class?

Super keyword in Method Overriding. The super keyword is used for calling the parent class method/constructor.

Does overriding works with inheritance?

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.

How do you stop behavior overriding in Java?

The final way of preventing overriding is by using the final keyword in your method. The final keyword puts a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and no other class can override the behavior.


1 Answers

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.

like image 154
Tanmay Patil Avatar answered Oct 09 '22 23:10

Tanmay Patil