JAVA static代码块,非static代码块,构造函数运行次序

今天写类测试了其中代码块的运行和static运行时机:

 

public class StaticClass {

	public static int j=8;
	static{
		j=9;
		System.out.println("j="+j+",in staic zone");
	}
	public StaticClass(){
		j=10;
		System.out.println("j="+j+",in the constructor");
	}
	{
		j=11;
		System.out.println("j="+j+",in the ordinary code zone");
	}


}

 

 

 

 

 

public class test {
public static void main(String []args){
         System.out.println("Hello world");
	 StaticClass sc;

}
}

 

 

 

 

 

 

 

 

 

 

运行结果:

Hello world

 

</pre><pre name="code" class="java">public class test {
public static void main(String []args){
         System.out.println("Hello world");
	 StaticClass sc=new StaticClass();

}
}

运行结果:

Hello world

j=9,in staic zone
j=11,in the ordinary code zone
j=10,in the constructor

 

结论:1,类中的static代码块只是在,当类被载入时被执行,且只被执行一次,静态块常用来执行类属性的初始化。使用new创建新对象时,会去加载类。

 

    2,类中各部分执行顺序是:static代码块-->非static代码块-->构造函数

           Java小菜,若有不对之处,请指教。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值