本章圍繞「復用」展開,核心機制是繼承。所有類默認繼承 Object,因此擁有 toString()、equals()、hashCode() 等方法。
@Override 註解可讓編譯器檢查是否真正覆寫;super.method()。toString():默認返回 類名@哈希碼,強烈建議覆寫輸出業務信息;equals():默認比較引用地址,值類型需覆寫比較內容;hashCode():配合 equals 用於哈希容器,覆寫 equals 必須覆寫 hashCode。super()(無參);super(參數) 調用父類帶參構造;super。Class1 c1 = new Class1(); Class2 c2 = new Class2(); // 繼承 Class1 Class3 c3 = new Class3(); // 繼承 Class2 c1.fun(); c2.fun(); c3.fun(); // 調用各自覆寫版本 c1.func(); c2.func(); c3.func(); // func 未覆寫,調用父類版本
編譯時看引用類型,運行時看對象實際類型(動態綁定)。
has-a 而非 is-a;class Class1 { void fun() { print("hello1"); } void func() { print("hello11111"); } }
class Class2 extends Class1 { void fun() { print("hello2"); } }
class Class3 extends Class2 { void fun() { print("hello3"); } }
輸出:hello1, hello2, hello3, hello11111, hello11111, hello11111。