尝试使用父类方法时Java调用子类方法 [英] Java calling subclass method when trying to use parent class method

查看:116
本文介绍了尝试使用父类方法时Java调用子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个班级,A和B,

If I have two classes, A and B,

public class A {
    public int test() {
        return 1;
    }
}

public class B extends A{
    public int test() {
        return 2;
    }
}

如果我这样做: A a1 = new B(),然后 a1.test()根据需要返回2而不是1。
这只是Java的一个怪癖,还是有这种行为的原因?

If I do: A a1 = new B(), then a1.test() returns 2 instead of 1 as desired. Is this just a quirk of Java, or is there some reason for this behavior?

推荐答案

不,那是正确(这是由于多态性)。所有方法调用都是对象操作,而不是引用类型。

No, that is correct (it is due to polymorphism). All method calls operate on object, not reference type.

这里你的对象的类型是 B,所以测试方法将调用 B类

Here your object is of type B, so test method of class B will be called.

这篇关于尝试使用父类方法时Java调用子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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