Java重载和继承规则

标签 java inheritance overloading

我一直在学习,因为我要参加考试,而且我对 Java 的大部分内容都没有太多问题,但我偶然发现了一条我无法解释的规则。这是一个代码片段:

public class A {

    public int method(Object o) {
        return 1;
    }

    public int method(A a) {
        return 2;
    }
}

public class AX extends A {

    public int method(A a) {
        return 3;
    }

    public int method(AX ax) {
        return 4;
    }
}

public static void main(String[] args) {
    Object o = new A();
    A a1 = new A();
    A a2 = new AX();
    AX ax = new AX();

    System.out.println(a1.method(o));
    System.out.println(a2.method(a1));
    System.out.println(a2.method(o));
    System.out.println(a2.method(ax));
}

这会返回:

1 3 1 3

虽然我希望它会返回:

1 3 1 4

为什么是a2的类型决定了AX中调用哪个方法?

我一直在阅读有关重载规则和继承的内容,但这似乎很模糊,以至于我无法找到确切的规则。任何帮助将不胜感激。

最佳答案

这些方法调用的行为由 Java Language Specification 规定和描述。 (引用第 8.4.9 节)。

When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).

在您的示例中,Java 编译器确定您正在调用方法的实例的编译类型最接近的匹配项。在这种情况下:

A.method(AX)

最接近的方法来自类型 A,签名为 A.method(A)。在运行时,动态调度是在 A 的 actual 类型(它是 AX 的一个实例)上执行的,因此这是实际调用的方法:

AX.method(A)

关于Java重载和继承规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11110631/

相关文章:

java - 无需转换对象即可访问通用方法

c++ - 检查对象的类型是否继承自特定类

java - 我对Java继承有相当基本的了解。有人可以解释该怎么做吗?

c# - 如何用重载和覆盖方法来解释这种行为?

delphi - 如何根据结果类型重载函数?

c++ - 在 C++ 中使用相同定义重载函数

java - Jython 中的随机性

java - Java框架中的空白框架

java - Android gson 无效 ClassCastException

java - Eclipse 'loading descriptor' 需要很长时间