class Grandparent {
public Grandparent() { System.out.println("GrandParent Created."); }
public Grandparent(String s) { System.out.println("GrandParent Created: " + s); }
}
class Parent extends Grandparent {
public Parent() {
super("Hello Grandparent"); // 必須是第一行
System.out.println("Parent Created");
}
}
class Child extends Parent {
public Child() { System.out.println("Child Created"); }
}
public class Test {
public static void main(String[] args) { new Child(); }
}
// 輸出順序:
// GrandParent Created: Hello Grandparent
// Parent Created
// Child Created
規則: 子類構造器首行隱式/顯式調用父類構造器;若父類無無參構造器,子類必須顯式 super(...);初始化順序:父類靜態 → 子類靜態 → 父類實例 → 父構造器 → 子類實例 → 子構造器。
super.method() 調用被覆蓋的父類方法。final 方法不可覆蓋(如 Object.getClass())。String、Integer)。public final class Address {
private final String detail;
private final String postCode;
public Address(String detail, String postCode) {
this.detail = detail;
this.postCode = postCode;
}
// 僅提供 getter,無 setter
public String getDetail() { return detail; }
public String getPostCode() { return postCode; }
@Override public boolean equals(Object o) { ... }
@Override public int hashCode() { ... }
}
優勢: 線程安全、可作 Map Key/Set 元素、防禦性拷貝簡化、緩存友好。
abstract class 可包含抽象方法(無實現)與具體方法/字段。AbstractType ref = new ConcreteImpl();public static final 常量、public abstract 方法。default 默認方法、static 靜態方法。private 私有方法。implements 多個接口,實現多重繼承效果。interface OneInterface { void f1(); }
interface TwoInterface extends OneInterface { void f2(); }
class Impl implements TwoInterface {
public void f1() { ... }
public void f2() { ... }
}
實現類必須實現父接口與子接口所有抽象方法才能實例化。
| 維度 | 抽象類 | 接口 |
|---|---|---|
| 本質 | 不完全的類,含狀態與行為 | 行為契約,無狀態(JDK8前) |
| 繼承數量 | 單繼承 | 多實現 |
| 構造器 | 有 | 無 |
| 適用場景 | 「is-a」強關聯,共享代碼/狀態 | 「can-do」能力擴展,跨層級復用 |