Java变量可见性

Geo*_*e V 0 java variables scope initialization disambiguation

我有以下代码:

public class Java0102
{
    public static void main(String[] args)
    {
        int x = 2;
        int y = 10;
        if (x == 2)
        {
            x = 5;
            int w = y * x;
        }
        System.out.println("W="+w);
        int W = x*y*w;
        y = x;
        System.out.println("New W="+w);
        System.out.println("X="+x);
        System.out.println("Y="+y);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在bluej上编译它时它说找不到符号 - 变量w但是因为if语句运行因为x == 2不应该java假设变量w被初始化并且存在吗?

Lui*_*oza 5

变量wif块代码中声明,这意味着它只能在该范围内访问:if语句的块代码.在该块之后,该变量w不再存在,因此编译器错误有效.

要解决此问题,只需在if语句之前声明并初始化变量.

int w = 1;
if (x == 2) {
    x = 5;
    w = y * x;
}
Run Code Online (Sandbox Code Playgroud)

从你在问题中的评论:

我认为如果调用一个方法并且在方法内部声明的变量是局部的,那么范围就会改变,因此在外部不可见.if语句是一回事吗?它改变了范围?

你混淆了类变量的概念,即字段和局部方法变量(通常称为变量).创建类的实例时,类中的字段将被初始化,而方法中的变量具有特定的范围,该范围取决于它们被声明的块代码.

这意味着,您可以编译并运行此代码(并不意味着您必须编写这样的代码):

public class SomeClass {
    int x; //field
    public void someMethod(int a, int b) {
        int x = a + b;
        //this refers to the variable in the method
        System.out.println(x);
        //this refers to the variable in the class i.e. the field
        //recognizable by the usage of this keyword
        System.out.println(this.x);
    }
}
Run Code Online (Sandbox Code Playgroud)