相关疑难解决方法(0)

方法重载null参数

我添加了三个带参数的方法:

public static  void doSomething(Object obj) {
    System.out.println("Object called");
}

public static  void doSomething(char[] obj) {
    System.out.println("Array called");
}

public static  void doSomething(Integer obj) {
    System.out.println("Integer called");
}
Run Code Online (Sandbox Code Playgroud)

当我调用时doSomething(null),编译器会将错误视为模糊方法.所以是问题,因为Integerchar[]方法,或IntegerObject方法呢?

java oop null overloading

128
推荐指数
3
解决办法
7万
查看次数

在Java中重载方法中使用null

可能重复:
NULL参数的方法重载

以下代码编译并正常运行.

public class Main
{
    public void temp(Object o)
    {
        System.out.println("The method with the receiving parameter of type Object has been invoked.");
    }

    public void temp(String s)
    {
        System.out.println("The method with the receiving parameter of type String has been invoked.");
    }

    public void temp(int i)
    {
        System.out.println("The method with the receiving parameter of type int has been invoked.");
    }

    public static void main(String[] args)
    {
        Main main=new Main();
        main.temp(null);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此代码中,要调用的方法是接受类型参数的方法 String

文档说.

如果多个成员方法都可访问并适用于方法调用,则必须选择一个为运行时方法调度提供描述符.Java编程语言使用选择最具体方法的规则.

但我不明白当代码中接受原语参数的方法之一 …

java null overloading

6
推荐指数
1
解决办法
4987
查看次数

标签 统计

java ×2

null ×2

overloading ×2

oop ×1