尝试使用父类方法时Java调用子类方法

标签 java inheritance

如果我有两个类,A 和 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 的一个怪癖,还是有某种原因导致这种行为?

最佳答案

这叫做 polymorphism .在运行时,将根据 a1 的“真实”类型调用正确的方法,在本例中为 B

正如维基百科所说:

The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run-time (this is called late binding or dynamic binding).

关于尝试使用父类方法时Java调用子类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266744/

相关文章:

java - netbeans 找不到此命名空间的库

java - 使用 XML 的 Spring Integration 与使用 Java DSL 的 Spring Integration 有什么区别?

Java日期格式转换 - 月份错误

java - 如何使用 BottomNavigationBar 保存 fragment 的状态?

java - java中如何将子类的输入提供给父类?

java - 从 Java 发送电子邮件时 SMTP 服务器挂起时的帮助

PHP 单例和继承

c++ - 继承和重载默认构造函数

java - 强制子类中对象的实例化

java - 制作任何东西的通用参数化类型