Java 实例变量和局部变量

Java 实例变量和局部变量,java,Java,我对java非常陌生。当我们声明一个局部变量时,可以根据需要在方法体中更改它。但当我们声明一个实例变量时,我们不能在类的主体中更改它 对不起,我的问题。我知道这很容易,但我不能完全理解 class Test { int x; x=10 // error:cannot find class x int a=10; public void Method() { int y; y=1;

我对java非常陌生。当我们声明一个局部变量时,可以根据需要在方法体中更改它。但当我们声明一个实例变量时,我们不能在类的主体中更改它 对不起,我的问题。我知道这很容易,但我不能完全理解

class Test {       
    int x;  
    x=10 // error:cannot find class x  
    int a=10;       
    public void Method() {  
        int y;  
        y=1;  
        y=11;  
    } 
}

x=10
被认为是一个语句,不能在类中的任何地方使用语句。它们必须包含在代码块中(在大括号之间),例如方法中初始值设定项块中,或构造函数中

class Test {       
    int x;
    int a=10;       
    {  
        // This is acceptable.
        x = 10;
    }

    // Constructor
    public Test() {
        // This is acceptable
        this.x = 10;        
    }

    // Overloaded Constructor
    public Test(int value) {
        // This is acceptable
        this.x = value;        
    }

    public void Method() {  
        int y;  
        y=1;  
        y=11; 
        // This is acceptable 
        x = 10;
    } 
}