代码块的小常识

加载顺序

简单说:

  1. 进行静态属性的初始化,若有显性赋值再赋值
  2. 进行静态代码块的加载(注意是随类的加载而加载的,也就是所只进行一次
  3. 再进行非静态的上述步骤,只是转变为非静态,注意(普通代码块是可以多次执行的,它是随着对象被new出来后而执行的)
  4. 最后在执行构造器

这里有很好的代码说明:

/**
 * 代码块 可以对类中的属性进行一些赋值
 static:
 static
 {
 }
 随着类的加载而执行一次;(所以静态快于非静态执行)
 只能操作类中的静态结构;

 非static:
 {
 }
 随着对象的创建而执行;
 可以操作类中的所有结构;
 
 注意:代码块优先于构造器执行;
 * @description
 * @author watermelonhit
 * @version 
 * @data 2021年3月13日上午11:50:16
 */
public class BlockTest {
public static void main(String[] args) {
	//调用类变量
	int num1=Son.id2;
	System.out.println("************");
	//创建对象
	Son son=new Son();//先完成类的加载,再进行对象的创建
	System.out.println("***********");
	Son son1=new Son();//由于上一次完成的类的加载,故静态代码块不执行了
}
}
class Father{
	static int id1=1;
	Father(){
		System.out.println("this is father constructor");
	}
	static 
	{
		System.out.println("this is father static block");
	}
	{
		System.out.println("this is father block");
	}	
}
class Son extends Father{
	static int id2=2;
	Son()
	{
		System.out.println("this is son constructor");
	}
	static 
	{
		System.out.println("this is son static block");
	}
	{
		System.out.println("this is son block");
	}
}

输出结果:

this is father static block
this is son static block
************
this is father block
this is father constructor
this is son block
this is son constructor
***********
this is father block
this is father constructor
this is son block
this is son constructor
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值