静态代码块 非静态代码块和构造函数执行顺序

本文详细解析了Java中类的加载与初始化过程,通过具体的类定义和实例化过程,展示了静态成员变量、非静态成员变量及构造函数的执行顺序,并分析了父类与子类在初始化时的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class B
{
static int a = 0;
{
System.out.println("B.scope is running");
a = 10 ;
}
static
{
System.out.println("B.static scope is running");
a = 20;
}
public B()
{
a = 30;
System.out.println("B.Constructor is running");
}

public static void main(String arg[])
{
System.out.println(B.a);
System.out.println(B.a);
B b1 = new B();
B b2 = new B();
System.out.println(b1.a);
System.out.println(b2.a);
System.out.println(B.a);

}

}

运行结果为:

B.static scope is running
20
20
B.scope is running
B.Constructor is running
B.scope is running
B.Constructor is running
30
30
30

当我们在使用B类时,JVM将B的定义装载,这时它调用了B的静态定义初始化和静态代码块 由于是静态的,尽管我们打印了两次,静态定义初始化和静态代码块都只执行了一次。构造函数是后于非静态代码块执行的.
在屏蔽了Class B中的main方法后,我们再写一个C类继承B类,如下:
class C extends B
{
static int c = 0;
static
{
c = 10;
System.out.println("C.static code is runnning and now c is " + c);

}
{
c = 20;
System.out.println("C.non-static code is runnning and now c is " + c);

}

public C()
{
c = 30;
System.out.println("C.constructor is running and now c is " + c);
}
public static void main(String args[])
{
System.out.println(C.c);
System.out.println(C.c);
C c1 = new C();
C c2 = new C();
System.out.println(c1.c);
System.out.println(c2.c);
System.out.println(C.c);

}
}

B.static scope is running
C.static code is runnning and now c is 10
10
10
B.scope is running
B.Constructor is running
C.non-static code is runnning and now c is 20
C.constructor is running and now c is 30
B.scope is running
B.Constructor is running
C.non-static code is runnning and now c is 20
C.constructor is running and now c is 30
30
30
30

在此描述一下c变化过程,虽然定义了两个对象c1,c2但其实只有一份共有的c,c被装载时先被初始化为0,后来执行静态代码块时被初始化为10,接着执行c1的非静态代码快时被初始化为20,然后是c1的构造函数被出化为30,然后轮到c2的非静态代码块,这是又重新被初始化回20,然后c2的构造函数,变为30.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值