gpt4 book ai didi

java - 使用原语及其包装器的方法重载

转载 作者:太空狗 更新时间:2023-10-29 22:55:42 24 4
gpt4 key购买 nike

我正在尝试制定在以下场景中使用的规则。请解释为什么我得到 2 个不同的输出。

场景 1 输出:我是一个对象。

class Test {

public static void main (String[] args) {

Test t = new Test();
byte b_var = 10;
t.do_the_test(b_var);
}

public void do_the_test(Character c) {

System.out.println("I am a character.");
}

public void do_the_test(Integer i) {

System.out.println("I am an integer.");
}

public void do_the_test(Object obj) {

System.out.println("I am an object.");
}
}

场景 2 输出:我是一个整数。

class Test {

public static void main (String[] args) {

Test t = new Test();
byte b_var = 10;
t.do_the_test(b_var);
}

public void do_the_test(char c) {

System.out.println("I am a character.");
}

public void do_the_test(int i) {

System.out.println("I am an integer.");
}

public void do_the_test(Object obj) {

System.out.println("I am an object.");
}
}

最佳答案

Java Language Specification这是关于方法签名解析的:

The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

在您的第二种情况下,涉及 int 的方法签名在没有自动装箱的情况下适用,但具有扩大的数字转换。在第一种情况下,需要扩大转换 自动装箱才能达到 Integer 签名;然而,Java 要么自动装箱要么原始转换,而不会两者兼而有之。

关于java - 使用原语及其包装器的方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27940321/

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