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

前端 未结 5 456
半阙折子戏
半阙折子戏 2020-12-01 21:16

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\";
    }         


        
相关标签:
5条回答
  • 2020-12-01 22:06

    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.

    0 讨论(0)
  • 2020-12-01 22:06

    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

    0 讨论(0)
  • 2020-12-01 22:12

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

    0 讨论(0)
  • 2020-12-01 22:14

    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.

    0 讨论(0)
  • 2020-12-01 22:14

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

    0 讨论(0)
提交回复
热议问题