考虑只有这些方法的类的主体:
Integer getA()
{
return 0;
}
Integer getB()
{
return 1;
}
void testJava1()
{
final Integer a1, b1;
if ((a1 = getA()) != null && (b1 = getB()) != null)
{
System.out.println(a1 + " and " + b1); // fine
}
}
void testJava2()
{
final Integer a1, b1;
final boolean condition = ((a1 = getA()) != null) && ((b1 = getB()) != null);
if (condition)
{
System.out.println(a1 + " and " + b1); // variable might have been not initialized???
}
}
void testJava3()
{
final Integer a1, b1;
final boolean conditionA = (a1 = getA()) != null;
final boolean conditionB = (b1 = getB()) != null;
if (conditionA && conditionB)
{
System.out.println(a1 + " and " + b1); // fine
}
}
void testJava4()
{
final Integer a1, b1;
final boolean conditionA = (a1 = getA()) != null;
final boolean conditionB = (b1 = getB()) != null;
final boolean conditionC = conditionA && conditionB;
if (conditionC)
{
System.out.println(a1 + " and " + b1); // fine
}
}
为什么testJava2
无法编译?编译器报告
variable might not have been initialized
如果condition
为b1
,则null
将为false,因此永远不会在b1
块中访问if
。为什么编译器不够智能才能检测到它?