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的啊,不需要生成特定的对象就可以执行的啊。

解决方案 »

  1.   


    public class Test {
      static int b=1;
      b=2;

    那你b是什么类型呢?
      

  2.   

    [Quote=引用 5 楼 ksqqxq 的回复:]
    引用 4 楼 didijiji 的回复:引用 2 楼 easyroom 的回复:就是语法错误。不允许这么写这是定义成员的部分,允许赋个初始值,不能在这里执行逻辑对一个成员赋值两次,第一次毫无意义么同意二楼的
      

  3.   

    语法规定的,除声明时赋值外,赋值语句只能在方法内部 或者 是代码块内
    public class Test {
      static int b=1;
      
      {
        b=2;
      }

    你也可以这么写
      

  4.   

    lz很有创新精神啊 打破了sun公司的制定的规则
      

  5.   

    我来给个权威的说法:)
    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 declaration
    Java Language Specification 15.1其实最好的Java书籍就是JSL