什么是int a = 0之间的本质区别;和int; α= 0;?

时间:2014-08-03 10:34:57

标签: java

int a=0;

int a; a=0;

它们之间的本质区别是什么?

我有这段代码:

btn1.setOnClickListener(new OnClickListener() {
    int a=0;

    int b;
    //   ^
    b=0;

我的IDE显示了一个红色的波浪形,我上面有^

picture of the code above

在Java匿名内部类中,为什么它会显示第二个语句的红色波浪形而不是第一个?

2 个答案:

答案 0 :(得分:3)

我不知道为什么你的IDE显示红色波浪形的地方,但问题在于

b=0;

线。那时,你就处于班级的顶层。您不能在那里进行分配,它们只能在方法,构造函数或初始化程序块中。 int a=0;有效的原因是它是成员声明的初始值设定项, 允许。

一个更简单的例子可能会使这更清楚:

class Example {

    int a = 0; // This is fine, it's an initializer on a member declaration

    int b;     // This is also fine, it's a member declaration

    b = 0;     // This is an error, it's an assignment that isn't in a method,
               // constructor, or initializer block

    {
        b = 0; // This is fine, because it's inside an *instance* initializer
               // block. These blocks are run when an instance is being
               // constructed, just before the constructor is called
    }

    static int c;

    static {
        c = 0; // This is fine, because it's inside a *static* initializer block
               // These blocks are run when the class (as a whole, not an 
               // instance) is being initialized
    }

    void method() {
        b = 0; // This is fine, because it's inside a method
    }
}

答案 1 :(得分:1)

在您上传的图片中,没有编码块,方法内没有类空间

你也可以使用第二个statemant参见:

public class myclass{

    int a;
    {
        a = 0;
    }

}

注意:这样的块称为初始化块