Java静态类初始化器与终结器

    静态类初始化器语法结构:

static
{
//语句
}

    静态类初始化器没有返回值,没有参数,其中的变量必须是static型,静态成员变量和静态初始化块级别相同。

public class Test 
{   
    public static int i;   
    static 
    {   
         i = 10;   
    }   
}  
public class Test 
{   
    public static int i = 10;   
}  
    这两段代码没什么区别, 两段示例代码编译之后的字节码完全一致。


    测试示例:

class Account {
	static int num = 0;
	public Account() {
		num++;
		System.out.println("aa");
	}
	static {
		num = 100;
		System.out.println("bb");
	}
}

public class cam2 {
	public static void main(String args[]) {
		Account a = new Account();
		System.out.println(a.num);
		Account b = new Account();
		System.out.println(b.num);
		System.out.println(Account.num);
		}
}

    输出结果:

bb

aa

101

aa

102

102

    从输出结果可看出静态类初始化块只执行了一次。




    终结器语法结构:

protected void finalize()
{
   //语句
}
    当垃圾达到一定数目且系统不繁忙时,垃圾回收线程会自动完成所有垃圾对象的内存释放,类似于C++中的析构函数。

class Account {
	int k = 0;
	protected void finalize() {
		System.out.println(k);
	}
}

public class cam2 {
	public static void main(String args[]) {
		Account a;
		a = new Account();
		a.k = 1;
		a = new Account();
		a.k = 2;
		System.gc();
	}
}

    输出结果为1,因为堆中的a.k = 1已为垃圾。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值