簡體   English   中英

調用靜態方法時“變量xxx可能尚未初始化”,該方法返回相同類型的變量和類型本身的相同名稱

[英]“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

為什么它會因下面顯示的錯誤而失敗? 我不確定JLS在哪里尋找限制做這樣的事情。

public class A {

    static A foo() {
        return null;
    }

    public static void main(String[] args) {
        A A = A.foo();
    }
}

編譯時出錯

A.java:14: error: variable A might not have been initialized
        A A = A.foo();
              ^
1 error

變量隱藏了同名的類。 這就是為什么有命名約定的部分原因。


正如帕特里夏在評論中指出的那樣,這在JLS中實際上被稱為模糊

在這些情況下, §6.5的規則指定將優先選擇變量而不是類型,並且將優先選擇類型而不是包。


在您的情況下,您會收到編譯錯誤,因為變量隱藏了類型,因為在方法調用之前處理了聲明。 這與執行以下操作相同:

public class A {
    public void foo() {
        String s = s.substring(0, s.length());
    }
}

你得到同樣的錯誤:

A.java:3: variable s might not have been initialized
        String s = s.substring(0, s.length());
                   ^
1 error

在評論中,你說你找不到JLS說你的建築是非法的。 它本身並不違法,因為模糊的結果是。 考慮兩個類的情況,你也可以因為模糊而得到不需要的電話,這不是非法的,只是令人困惑:

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()");
        }
    }
}

您認為輸出是什么?

$ javac A.java
$ java A
A.foo()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM