public class Test {
static int b=1;
b=2;
}
public class Test {
static int b=1;
Test.b=2;
} 这两段程序代码都不能编译通过,为什么?以前在csdn碰到过这个问题:public class Test {
int b=1;
b=2;
}
以上程序提示错误都是一样的,需要标识符。解释是这样的:
类加载的时候 int b=1;
b=2;
就会执行,但是这个时候还没有生成一个特定的对象,就是说b=2;这条语句中的b没有指向特定的对象,所以会提示“需要标识符”的错误,但是我以上的程序是加了static的啊,不需要生成特定的对象就可以执行的啊。
static int b=1;
b=2;
}
public class Test {
static int b=1;
Test.b=2;
} 这两段程序代码都不能编译通过,为什么?以前在csdn碰到过这个问题:public class Test {
int b=1;
b=2;
}
以上程序提示错误都是一样的,需要标识符。解释是这样的:
类加载的时候 int b=1;
b=2;
就会执行,但是这个时候还没有生成一个特定的对象,就是说b=2;这条语句中的b没有指向特定的对象,所以会提示“需要标识符”的错误,但是我以上的程序是加了static的啊,不需要生成特定的对象就可以执行的啊。
public class Test {
static int b=1;
b=2;
}
那你b是什么类型呢?
引用 4 楼 didijiji 的回复:引用 2 楼 easyroom 的回复:就是语法错误。不允许这么写这是定义成员的部分,允许赋个初始值,不能在这里执行逻辑对一个成员赋值两次,第一次毫无意义么同意二楼的
public class Test {
static int b=1;
{
b=2;
}
}
你也可以这么写
Each expression occurs in either:
• The declaration of some (class or interface) type that is being declared: in a
field initializer, in a static initializer, in an instance initializer, in a constructor
declaration, in an annotation, or in the code for a method.
• An annotation of a package or of a top-level type declarationJava Language Specification 15.1其实最好的Java书籍就是JSL