让我们看看以下代码段中的简单Java代码:
public class Main {
private int temp() {
return true ? null : 0;
// No compiler error - the compiler allows a return value of null
// in a method signature that returns an int.
}
private int same() {
if (true) {
return null;
// The same is not possible with if,
// and causes a compile-time error - incompatible types.
} else {
return 0;
}
}
public static void main(String[] args) {
Main m = …Run Code Online (Sandbox Code Playgroud) 考虑两个重载:
public void add(Integer value)
{
add(value == null ? null : value.doubleValue());
}
Run Code Online (Sandbox Code Playgroud)
和
public void add(Double value)
{
// some code here
}
Run Code Online (Sandbox Code Playgroud)
如果我用a的null实例调用第一个Integer,那么三元条件是否会调用a的重载Double,或者它是否调用自身?
在我的机器上它调用Double重载,但这是定义良好的Java吗?JLS对此有何评价?
在Java中我这样写的时候
public int method(boolean b) {
if (b)
return null;
else
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨incompatible types,但如果用速记替换它
public int method(boolean b) {
return (b ? null : 0);
}
Run Code Online (Sandbox Code Playgroud)
编译器不会抱怨,而且会有一个NPE.所以我的问题是
NPE?