“variable xxx might not have been initialized” when calling static method that returns variable of the same type and the same name of the type itself

巧了我就是萌 提交于 2020-01-30 05:50:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!