在学习java程序初始化时碰到的问题及解决

文章讨论了Java中类变量的声明与使用规则。在代码示例中,虽然`a=2`在声明之前,但由于`a`是类变量,其作用域覆盖整个类,所以在静态初始化块中可以使用。然而,对于类变量的引用,如果在声明前使用并出现在类或静态初始化块中,且未在赋值的左侧,会导致编译错误。文章还提到了静态块的执行顺序和继承时的影响。
摘要由CSDN通过智能技术生成

起因:代码里a=2前不加int,声明在后面,不懂为啥

public class TestStatic{
  static {a=2;}
  static int a=1;
  static int b=3;
  static {b=4;}
  public static void main(String[] args){
    System.out.println(a);
    System.out.println(b);}
  }
}

去stackoverflow提问后总结大佬们的回答:

1.局部变量是在赋值前必须先声明,代码里a不是局部变量,a是类变量

局部变量的作用域是声明了这个变量到block的最后。而不管静态还是非静态的字段(feilds)都是成员,作用域是整个类:

The scope of a declaration of a member m declared in or inherited by a class or interface C (§8.2, §9.2) is the entire body of C, including any nested class or interface declarations. If C is a record class, then the scope of m additionally includes the header of the record declaration of C.

 a的作用域是整个testStatic,所以声明前也能用,和在函数定义前调用函数是一个道理

void f() {
    g(); // can call g here!
}

void g() {}

但以下情况会报错:

class Foo {
    static int b = a; // changing this to Foo.a works
    static int a = 0;
}

 因为:给类变量赋值的引用出现以下情况会报错:1.引用是类变量的初始化或是在类的静态初始化程序(静态代码块)里。2.。。。。不会翻译了我擦唉

References to a field are sometimes restricted, even through the field is in scope. The following rules constrain forward references to a field (where the use textually precedes the field declaration) as well as self-reference (where the field is used in its own initializer).

For a reference by simple name to a class variable f declared in class or interface C, it is a compile-time error if:

  • The reference appears either in a class variable initializer of C or in a static initializer of C (§8.7); and

  • The reference appears either in the initializer of f's own declarator or at a point to the left of f's declarator; and

  • The reference is not on the left hand side of an assignment expression (§15.26); and

  • The innermost class or interface enclosing the reference is C.

  • 参见8.3.3章节的文档Chapter 8. Classes (oracle.com)

2.java - In what order do static blocks and initialization blocks execute when using inheritance? - Stack Overflow 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值