Thinking in Java(5)-finalize()和初始化

来源:互联网 发布:淘宝排除同款 编辑:程序博客网 时间:2024/05/15 16:12

1.贴上书中一段代码:

public class Book {    boolean checkedOut = false;    Book(boolean checkOut)    {        checkedOut = checkOut;    }    void checkIn()    {        checkedOut = false;    }    protected void finalize()    {        if (checkedOut)            System.out.println("Error: checked out");    }public static void main(String[] args){    Book novel = new Book(true);    novel.checkIn();    new Book(true);    System.gc();}}

程序意在说明,由于Java先进的垃圾回收机制,即使你不显式调用finalize()方法,objects不用的时候,虚拟机会自动执行finalize()方法回收对象。System.gc()用于提醒虚拟机进行垃圾回收。
2.关于初始化,常量就不说了,在一个类当中,无论变量定义在方法之前还是方法之后,都会在方法之前进行初始化,static数据初始化位于非static数据初始化之前 。有继承时,static变量初始完了后,先初始化父类,然后是子类。
总结起来就是:JAVA类首次装入时,会对静态成员变量或方法进行一次初始化,但方法不被调用是不会执行的,静态成员变量和静态初始化块级别相同,非静态成员变量和非静态初始化块级别相同。初始化顺序:先初始化父类的静态代码—>初始化子类的静态代码–>(创建实例时,如果不创建实例,则后面的不执行)初始化父类的非静态代码(变量定义等)—>初始化父类构造函数—>初始化子类非静态代码(变量定义等)—>初始化子类构造函数, 类只有在使用New调用创建的时候才会被JAVA类装载器装入创建类实例时,首先按照父子继承关系进行初始化类实例创建时候,首先初始化块部分先执行,然后是构造方法;然后从本类继承的子类的初始化块执行,最后是子类的构造方法类消除时候,首先消除子类部分,再消除父类部分.
书中有一个练习题:

/* Create class with static String field initialized at point of definition and* another one initialized by the static block.  Add static method that prints* both fields and demonstrates that they are both initialized before thay are* used.*/class Go {    static String s1 = "run";    static String s2, s3;    static {        s2 = "drive car";        s3 = "fly plane";    System.out.println("s2 & s3 initialized");    }    static void how() {        System.out.println(s1 + " or " + s2 + " or " + s3);    }    Go() { System.out.println("Go()"); }    }public class ExplicitStaticEx {    public static void main(String[] args) {        System.out.println("Inside main()");        Go.how();        System.out.println("Go.s1: " + Go.s1);          }    static Go g1 = new Go();    static Go g2 = new Go();}

结果是什么呢?先自己做一下。
载入类时,所有static变量被初始化,static代码块有方法(System.out.println())调用,首先打印”s2 & s3 initialized”,创建对象g1和g2会调用构造方法,打印两个”Go()”,然后执行主方法main(),打印”Inside main()”,接下来执行how方法,打印”run or drive car or fly plane”,最后执行”System.out.println(“Go.s1: ” + Go.s1)”,所以,结果是:

s2 & s3 initializedGo()Go()Inside main()run or drive car or fly planeGo.s1: run

Java中也有被成为实例初始化的类似语法,用来初始化每一个对象的非静态变量。和静态语句块一样的,只不过少了static。
如书中的这道题:

// Create a class with a String that is initialized using instance initialization class Tester {    String s;    {        s = "Initializing string in Tester";        System.out.println(s);    }    Tester() {        System.out.println("Tester()");    }    public static void main(String[] args) {        new Tester();       }    }

结果:

Initializing string in TesterTester()
0 0
原创粉丝点击