覆盖java中的方法,然后将对象转换为父类行为 [英] Overriding methods in java and then casting object to parent class behavior

查看:127
本文介绍了覆盖java中的方法,然后将对象转换为父类行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类A和一个子类,B和B从A中覆盖一个方法f。

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
    }
}

我创建了一个类型的对象B,b,并将其转换为A类并将其分配给A,a类型的变量,然后在a上调用方法f。现在我希望调用父类的方法,因为我正在处理类型A的对象,但事实并非如此,它调用方法的b版本(打印B而不是A)下面的代码。)

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?

推荐答案

这是多态的基础



这应该是这样的。

根据以下内容动态调度(选择/调用)任何方法对象的实际类型,而不是引用它的类型。

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.

希望这会有所帮助。

这篇关于覆盖java中的方法,然后将对象转换为父类行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆