Java重载和继承规则 [英] Java overloading and inheritance rules

查看:103
本文介绍了Java重载和继承规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been studying because I have an exam and I don't have many problems with most of Java but I stumbled upon a rule I can't explain. Here's a code fragment:

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 3

虽然我希望它能够回归:

While I would expect it to return:

1
3
1
4

1 3 1 4

为什么a2的类型决定调用哪种方法在AX?

Why is it that the type of a2 determines which method is called in AX?

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

I've been reading on overloading rules and inheritance but this seems obscure enough that I haven't been able to find the exact rule. Any help would be greatly appreciated.

推荐答案

这些方法调用的行为由 Java语言规范(参考部分8.4.9)。

The behavior of these method calls is dictated and described by the Java Language Specification (reference section 8.4.9).


调用方法时(第15.12节),实际参数的数量(和
任何显式类型参数)和编译时使用编译时类型的
参数来确定将被调用的
方法的签名(第15.12.2节)。如果调用
的方法是实例方法,则使用动态方法查找(第15.12.4节),在运行时确定要调用的实际方法是

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编译器确定与您调用方法的实例的编译类型最接近的匹配项。在这种情况下:

In your example, the Java compiler determines the closest match on the compile type of the instance you are invoking your method on. In this case:

A.method(AX)

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

The closest method is from type A, with signature A.method(A). At runtime, dynamic dispatch is performed on the actual type of A (which is an instance of AX), and hence this is the method that is actually called:

AX.method(A)

这篇关于Java重载和继承规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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