相关疑难解决方法(0)

基于参数的实际类型重载方法选择

我正在尝试这段代码:

interface Callee {
    public void foo(Object o);
    public void foo(String s);
    public void foo(Integer i);
}

class CalleeImpl implements Callee
    public void foo(Object o) {
        logger.debug("foo(Object o)");
    }

    public void foo(String s) {
        logger.debug("foo(\"" + s + "\")");
    }

    public void foo(Integer i) {
        logger.debug("foo(" + i + ")");
    }
}

Callee callee = new CalleeImpl();

Object i = new Integer(12);
Object s = "foobar";
Object o = new Object();

callee.foo(i);
callee.foo(s);
callee.foo(o);
Run Code Online (Sandbox Code Playgroud)

这打印foo(Object o)三次.我希望方法选择考虑到真实的(不是声明的)参数类型.我错过了什么吗?有没有办法修改这个代码,以便打印foo(12), …

java oop

107
推荐指数
4
解决办法
5万
查看次数

当参数是文字空值时,如何选择重载方法?

我在测验中遇到了这个问题,

public class MoneyCalc {

   public void method(Object o) {
      System.out.println("Object Verion");
   }

   public void method(String s) {
      System.out.println("String Version");
   }

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

该程序的输出是"String Version".但是我无法理解为什么将null传递给重载方法会选择字符串版本.null是一个String变量,指向什么?

但是当代码更改为时,

public class MoneyCalc {

   public void method(StringBuffer sb) {
      System.out.println("StringBuffer Verion");
   }

   public void method(String s) {
      System.out.println("String Version");
   }

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

它给出了一个编译错误,说"方法方法(StringBuffer)对于MoneyCalc类型是不明确的"

java overloading

97
推荐指数
2
解决办法
1万
查看次数

在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 ×3

overloading ×2

null ×1

oop ×1