简体   繁体   English

为什么这个 java 代码没有给出“已定义”错误?

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

Why does this java code not give an already defined error for y?为什么这个 java 代码没有给出 y 的已定义错误? I can understand why, because it is in a loop.我能理解为什么,因为它是在一个循环中。 But it does not seem logical.但这似乎不合逻辑。

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

If I run this code it results in an error:如果我运行此代码,则会导致错误:

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

Because you are declaring y twice.因为您要声明 y 两次。 Once outside the loop int y = 0;一旦在循环外int y = 0; and once inside the loop int y = i;并且一旦进入循环int y = i; . .

You should replace int y = i;你应该替换 int y = i; with y=i; y=i; . . This should solve your problem.这应该可以解决您的问题。

First declared y variable covers a broader scope including your for loop block.首先声明的y变量涵盖了更广泛的 scope ,包括您的 for 循环块。 So it is visible inside for loop already.所以它已经在 for 循环中可见了。 Because of this, redefining it inside for loop throws compilation error因此,在 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);
    }
}
}

So if you really want to use variable y , then don't define it again, and remove the int type before it.所以如果你真的想使用变量y ,那么不要再定义它,并删除它之前的int类型。

Short answer: You cannot define the same variable twice in the same scope.简短回答:您不能在同一个 scope 中定义同一个变量两次。 The scope of your for loop occurs inside the method's scope, so y is already defined. for循环的 scope 发生在方法的 scope 内,因此y已经定义。

Long answer: This is a misunderstanding of variable scope.长答案:这是对变量 scope 的误解。 I'll try to explain:我将尝试解释:

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

I labeled the respective scopes in the above code and where they begin and end.我在上面的代码中标记了各自的范围以及它们的开始和结束位置。

In the above example, once the for loop ends, int y goes out of scope and can no longer be referenced.在上面的例子中,一旦for循环结束, int y就会从 scope 中退出,并且不能再被引用。 So after end loop scope , System.out.println(y) will fail, as y no longer exists.所以在end loop scope之后, System.out.println(y)将失败,因为y不再存在。

In the second example, y already exists in method scope.在第二个示例中, y已经存在于方法 scope 中。 You cannot redefine a variable with the same name in a "child" scope, which is why your second example fails.您不能在“子”scope 中重新定义具有相同名称的变量,这就是您的第二个示例失败的原因。

There is one exception to this, however.然而,有一个例外。 You may define a variable with an identical name to one defined in class scope.您可以定义一个与 class scope 中定义的变量同名的变量。 So this would work:所以这会起作用:

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

For class scope, if there is an identically named variable in method scope, you must qualify it with this .对于 class scope,如果方法 scope 中有同名变量,则必须使用this对其进行限定。 So to reference the class scoped y variable inside main , you would use this.y .因此,要在main中引用 class 范围内的y变量,您可以使用this.y This is why you will commonly see variables assigned in constructors and setters like this:这就是为什么您通常会看到在构造函数和设置器中分配的变量,如下所示:

public class SomeClass {
    int property

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

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

Another example:另一个例子:

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

If you were to do this, this would have no effect, as you did not specify this.property .如果您要这样做,这将无效,因为您没有指定this.property You'd simply be setting the value of property to itself.您只需将属性的值设置为自身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这个 Java 代码会给出“字符串索引超出范围”错误? - Why does this Java code give an " String index out of range " error? 为什么下面的Java代码会给出StackOverflow错误? - Why does the java code below give StackOverflow error? 为什么以下代码返回错误消息类型Person已经被定义。 班级人员有什么问题? - Why does the following code return the error message The type Person is already defined. What is the issue with the Class Person? 为什么 Java 上的 instanceof 会出现编译错误? - Why does instanceof on Java give a compilation error? 为什么Java编译器在以下代码中为LinkedListDescingIterator给出“错误:找不到符号”? - Why does Java compiler give "error: cannot find symbol" for LinkedList descendingIterator in the following code? Java 中的类型已定义错误 - The Type is Already Defined Error in Java 为什么这段通用代码会产生编译错误 - Why does this generic piece of code give a compilation error 为什么此代码给出错误作为实际的形式参数? - why does this code give error as actual formal parameter? 为什么这段显示图像的代码在构建到 jar 中时会给出“错误”? - Why does this code displaying an image give an “”error“” when build into jar? 为什么 if 语句“if(1)”在 Java 中给出错误,但在 C++ 中却成立? - Why does the if statement "if(1)" give error in Java but it holds true in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM