Thinking In Java 第五章 初始化与清理

1、用构造器确保初始化。

2、区分方法重载的规则:每个重载的方法都必须有独一无二的参数类型列表。

3、涉及基本类型的重载,基本类型能从一个“较小”的类型自动提升至一个“较大”的类型。

4、不能以返回值区分重载方法:有时候并不关心方法的返回值,想要的只是方法调用的其他效果,此时可能会调用方法而忽略其返回值。

5、this关键字:<1>表示调用方法的哪个对象;<2>构造器中调用重载的构造器。

6、清理:终结处理和垃圾回收;<1>对象可能不被垃圾回收;<2>垃圾回收并不等于“析构”;<3>垃圾回收只与内存有关。

7、finalize()方法验证终结条件;下例的终结条件是:所有的Book对象在被当作垃圾回收前都应该被签入(check in)。但在main()方法中,由于程序员的错误,有一本书未被签入。要是没有finalize()来验证终结条件,将很难发现这种缺陷。

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");
			try {
				super.finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
	}
}

public class TerminationCondition {

	public static void main(String[] args) {
		Book novel = new Book(true);
		// Proper cleanup;
		novel.checkIn();
		// Drop the reference, forget to clean up;
		new Book(true);
		// Force garbage collection & finalization;
		System.gc();
	}
}

8、垃圾回收期如何工作:自适应:停止-复制,标记-清扫。

9、即使变量定义散布于方法定义之间,它们仍旧会在任何方法(包括构造器)被调用之前得到初始化。

10、静态初始化只有在必要时刻才会进行。静态初始化动作只执行一次。

猜你喜欢

转载自blog.csdn.net/weixin_39306760/article/details/87200232