问题
Why does it fail with the error shown below? I'm not sure where in the JLS to look for the restriction to do something like this.
public class A {
static A foo() {
return null;
}
public static void main(String[] args) {
A A = A.foo();
}
}
Error at compile time
A.java:14: error: variable A might not have been initialized
A A = A.foo();
^
1 error
回答1:
The variable hides the class of the same name. That's part of why there are naming conventions.
As Patricia notes in the comments, this is actually known in the JLS as obscuring:
In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.
In your case, you get a compilation error because the variable hides the type, as the declaration is treated before the method call. It's the same as doing the following:
public class A {
public void foo() {
String s = s.substring(0, s.length());
}
}
You get the same kind of error:
A.java:3: variable s might not have been initialized String s = s.substring(0, s.length()); ^ 1 error
In the comments, you say you don't find where the JLS says your construction is illegal. It's not illegal in itself, the result due to the obscuring is. Consider the case with 2 classes, where you can also get unwanted calls due to the obscuring, which is not illegal, just confusing:
public class A {
public void foo() {
System.out.println("A.foo()");
}
public static void main(String[] args) {
A B = new A();
B.foo();
}
public static class B {
public static void foo() {
System.out.println("B.foo()");
}
}
}
What do you think the output is?
$ javac A.java $ java A A.foo()
来源:https://stackoverflow.com/questions/13961056/variable-xxx-might-not-have-been-initialized-when-calling-static-method-that-r