Java 中的私有、静态和变量范围

Private, Static, and scope of variables in Java

在我的 Java class 中,我们刚刚了解了作用域。所谓博学,我的意思是它被简单地提到过一次,之后就再也没有提到过。发布了一些问题,我无法理解两段代码之间的区别。第一个:

public class Shadow3 {
    private static int i = 99;
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }
        System.out.println(i);
    }
}

第二个:

public class Shadow4 {
    private int i;
    public void doSomething(int n) {
        for (int i = 0; i < n; i++) {
            System.out.println(i);
        }
    }
    public static void main(String[] args) {
        new Shadow4().doSomething(9);
    }
}

我理解第一个的错误不是变量被声明了两次,而是我不明白为什么在Shadow class中声明的变量范围没有到达main导致重复错误的方法。我也明白为什么在第一段代码中,变量 i 在 for 循环中使用时不能声明为 private static,因为 i 在 for 循环中的值是临时的,但我不明白第二段代码中的变量 i 是有效的,因为它仍然是私有的。

I don't understand why the scope of the variable declared in the Shadow class doesn't reach the main method to cause a duplication error.

class变量的范围确实到达了main方法。但课程是关于阴影的。应该不会有任何错误。

the variable i cannot be declared as private static when it is then used in the for loop, because the values of i in the for loop are temporary,

For 循环变量是临时的并且是局部范围的,是的,但是您的推理是不正确的。您不能将局部变量声明为 privatestatic。就是这样。

I don't understand how then the variable i in the second piece of code is valid, because it is still private.

private 不是问题。该变量可以是默认的、受保护的或 public。该代码仍然有效。事实上,两个代码示例都有效。

首先,您可以使用 Shadow3.i 引用静态变量,对于另一个,您有一个实例变量,因此在 doSomething 方法中,您将使用 this.iShadow4.this.i