gpt4 book ai didi

java - java中的方法规则重载解释

转载 作者:行者123 更新时间:2023-11-30 09:10:20 25 4
gpt4 key购买 nike

我尝试了解使用 java 编译器的重载规则。

这对我来说太难了。

public class Main {

public static void var(Long x) {
System.out.println("Long");
}

public static void var(int... x) {
System.out.println("int... x");
}


public static void main(String... args) {
var(5);
}
}

输出:

int...

在互联网上我发现了下一条规则:

  1. Primitive Widening > Boxing > Varargs.
  2. Widening and Boxing (WB) not allowed.
  3. Boxing and Widening (BW) allowed.
  4. While overloading, Widening + vararg and Boxing + vararg can only be used in a mutually exclusive manner i.e. not together.
  5. Widening between wrapper classes not allowed

但我不能将此规则应用于此代码行为。

你能帮帮我吗?

我的错误版本:

装箱 int -> Integer 并扩大到 Long

附加问题

public class Main {

public static void var(Object x) {
System.out.println("Object");
}

public static void var(int... x) {
System.out.println("int... x");
}


public static void main(String... args) {
var(5);
}
}

输出:

object

最佳答案

boxing int to Integer and widening to Long

虽然 intInteger 装箱很好,但是 IntegerLong 不是有效的加宽。 Long 不是 Integer 的父类(super class)型。所以这是无效的。一种选择是加宽,然后是装箱。但是这种转换在 Java 中是不允许的。所以剩下的唯一选择就是使用可变参数。

关于java - java中的方法规则重载解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22593593/

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