gpt4 book ai didi

java - 方法重载包括父类和子类

转载 作者:行者123 更新时间:2023-11-30 06:12:53 24 4
gpt4 key购买 nike

为什么下面的代码会打印 "string" ?为什么没有错误,因为方法调用不明确?

class Mixer {
void print(String s) {
System.out.println("string");
}

void print(Object o) {
System.out.println("object");
}


public static void main(String[] args) {
Mixer m = new Mixer();
m.print(null);
}
}

最佳答案

说明

选择String方法是因为它是这些类型中最具体的。

由于这两种方法都是可访问并且适用,因此 Java 选择这两种方法中最具体的,这在 Java 语言中进行了描述详细规范。

参见JLS§15.12.2其中说:

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

JLS§15.12.2.5列出用于确定最具体方法的所有规则。

<小时/>

示例

看看以下方法:

public void foo(Object o) { ... }
public void foo(AbstractCollection<String> o) { ... }
public void foo(AbstractList<String> o) { ... }
public void foo(ArrayList<String> o) { ... }

对于每种方法,指定的类型都会变得更具体,如果您给出ArrayListnull,那么它将首先使用最低的方法。

关于java - 方法重载包括父类和子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49841396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com