静态类初始化器
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已为垃圾