繁体   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