簡體   English   中英

為什么這個 java 代碼沒有給出“已定義”錯誤?

[英]Why does this java code not give an “is already defined ” error?

為什么這個 java 代碼沒有給出 y 的已定義錯誤? 我能理解為什么,因為它是在一個循環中。 但這似乎不合邏輯。

class AlreadyDefined 
{
    public static void main(String[] args)
    {
        //int y = 0; //-- enable this for already defined error 
        for(int i = 0; i < 5; i++) 
        {
            int y = i; //not already defined 
            System.out.println(i);
        }
    }
}

如果我運行此代碼,則會導致錯誤:

class AlreadyDefined 
{
    public static void main(String[] args)
    {
        int y = 0;
        for(int i = 0; i < 5; i++) 
        {
            int y = i; //already defined 
            System.out.println(i);
        }
    }
}

因為您要聲明 y 兩次。 一旦在循環外int y = 0; 並且一旦進入循環int y = i; .

你應該替換 int y = i; y=i; . 這應該可以解決您的問題。

首先聲明的y變量涵蓋了更廣泛的 scope ,包括您的 for 循環塊。 所以它已經在 for 循環中可見了。 因此,在 for 循環中重新定義它會引發編譯錯誤

class AlreadyDefined 
{
public static void main(String[] args)
{
    int y = 0; //this variable is global in aspect to your for loop
    for(int i = 0; i < 5; i++) 
    {
        int y = i; //your y variable is visible in this for loop block
                   //so redefining it would throw a compiler error
        System.out.println(i);
    }
}
}

所以如果你真的想使用變量y ,那么不要再定義它,並刪除它之前的int類型。

簡短回答:您不能在同一個 scope 中定義同一個變量兩次。 for循環的 scope 發生在方法的 scope 內,因此y已經定義。

長答案:這是對變量 scope 的誤解。 我將嘗試解釋:

class AlreadyDefined // begin class scope
{

    public static void main(String[] args){ // begin method scope

        for(int i = 0; i < 5; i++){ // begin loop scope. 
            /// This scope also includes variables from method scope
            int y = i; 
            System.out.println(i);
        } // end loop scope

    } // end method scope

} // end class scope

我在上面的代碼中標記了各自的范圍以及它們的開始和結束位置。

在上面的例子中,一旦for循環結束, int y就會從 scope 中退出,並且不能再被引用。 所以在end loop scope之后, System.out.println(y)將失敗,因為y不再存在。

在第二個示例中, y已經存在於方法 scope 中。 您不能在“子”scope 中重新定義具有相同名稱的變量,這就是您的第二個示例失敗的原因。

然而,有一個例外。 您可以定義一個與 class scope 中定義的變量同名的變量。 所以這會起作用:

class AlreadyDefined // begin class scope
{
    static int y = 0; // Defining variable with identical name.

    public static void main(String[] args){ // begin method scope

        for(int i = 0; i < 5; i++){ // begin loop scope
            int y = i; // This still works
            System.out.println(i);
        } // end loop scope

    } // end method scope

} // end class scope

對於 class scope,如果方法 scope 中有同名變量,則必須使用this對其進行限定。 因此,要在main中引用 class 范圍內的y變量,您可以使用this.y 這就是為什么您通常會看到在構造函數和設置器中分配的變量,如下所示:

public class SomeClass {
    int property

    public SomeClass(int property) {
        this.property = property;
    }

    public void setProperty(int property) {
        this.property = property;
    }
}

另一個例子:

    public void setProperty(int property) {
       property = property;
    }

如果您要這樣做,這將無效,因為您沒有指定this.property 您只需將屬性的值設置為自身。

暫無
暫無

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

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