我想知道为什么下面的代码不起作用:
System.out.print(null);
response.getWriter().print(null);
但是下面的方法有效:
String s = null;
System.out.print(s);
response.getWriter().print(s);
传递 null
与传递 null
引用相比有什么区别?
已编辑:前面提到的不起作用表示编译错误。
最佳答案
这是因为您可以传递对象
或字符串
。由于 null
可以同时容纳这两种方法,因此编译器不知道使用哪种方法,从而导致编译错误。
方法定义:
相反,如果您提供 Object
或 String
变量(即使它具有 null
值),编译器就会知道哪个方法使用。
编辑:这有更好的解释 in this answer 。至于指向Java规范的内部链接,可以阅读here ,这种情况适合这里:
The informal intuition is that one method is more specific than another **if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
It is possible that no method is the most specific, because there are two or more methods that are maximally specific.
关于Java - 将 null 作为参数传递给 print(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14784697/