静态类初始化器语法结构:
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已为垃圾。