Java类初始化顺序

1)如果有父类,先初始化父类
2)类只被初始化一次,即类中的静态变量及静态代码块只在第一次加载时执行一次
3)类第一次初始化时先初始化静态变量,执行静态代码块
4)执行完静态代码后先初始化成员变量,然后执行构造器。

例:
package com.zsoft.test;

public class ClassLoadTest {
	public static void main(String[] args){
		new Circle();
	}
}

class Draw{
	public static String hello = "say hello!";

	static{
		System.out.println(hello);
	}
	
	public Draw(){
		System.out.println("draw construction");
	}
	
	public Draw(String type) {
		System.out.println(type + " draw construction");
	}
}


class Shape{
	public static Draw drawStatic = new Draw("shap static");
	private Draw draw = new Draw("shap");
	
	public Shape(){
		System.out.println("shap construction");
	}
}


class Circle extends Shape {
	private Draw draw = new Draw("circle");
	public static Draw drawStatic = new Draw("circle static");
	public Circle(){
		System.out.println("circle construction");
	}
}




输出:
say hello!
shap static draw construction
circle static draw construction
shap draw construction
shap construction
circle draw construction
circle construction
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值