導(dǎo)語:有人會(huì)問java有沒有和c 一樣的析構(gòu)函數(shù),我覺得嚴(yán)格意義上是沒有的,因?yàn)閖ava有垃圾回收機(jī)制,雖然有finalize()函數(shù),但是該函數(shù)并不具備c 析構(gòu)函數(shù)的功能
public class Book { private String bookName; public Book(String bookName) { this.bookName = bookName; System.out.println(bookName ' is created'); } @Override protected void finalize() throws Throwable { super.finalize(); System.out.println(bookName ' is freed'); }}public class Test { public static void main(String args[]) { Book l1 = new Book('book1'); Book l2 = new Book('book2'); l1 = l2 = null; System.gc(); }}
輸出結(jié)果:
book1 is created
book2 is created
book2 is freed
book1 is freed
聯(lián)系客服