面向過程:數據(結構體)與行為(函數)分離,邏輯分散,維護困難。面向對象 (OOP):將數據與操作數據的方法封裝在**類**中,以**對象**為基本運行單元,三大特性:封裝、繼承、多態。
new ClassName() 在堆內存分配,每次 new 產生獨立對象,互不影響。方法簽名 = 方法名 + 參數類型列表(順序敏感)。與返回值、參數名、修飾符、拋出異常無關。
public void print(int a, String b) {}
public void print(String b, int a) {} // 參數順序不同 → 重載合法
public int print(int a, String b) {} // 僅返回值不同 → 編譯錯誤(非重載)
重載規則:同一類中,方法名相同,參數列表不同(類型、個數、順序任意一項)。
void 都不寫。public class Person {
private String name;
private int age;
// 無參構造器
public Person() {}
// 全參構造器
public Person(String name, int age) {
this.name = name; // this 區分字段與參數同名
this.age = age;
}
}
| 用法 | 說明 | 示例 |
|---|---|---|
this.field | 訪問當前對象字段(區分同名參數/局部變量) | this.name = name; |
this.method() | 調用當前對象其他方法 | this.init(); |
this(...) | 構造器間調用,**必須放首行** | public Person() { this("unknown", 0); } |
return this | 鏈式調用返回當前對象 | public Person setName(String n) { this.name=n; return this; } |
| 傳遞當前對象 | 作為參數傳給其他方法 | other.process(this); |
Person p = new Person("Alice", 20);
// 棧:p (引用) ──▶ 堆:Person 對象 { name="Alice", age=20 }
// 再執行:Person q = p;
// 棧:q (引用) ──▶ 同一堆對象
// p.name = "Bob" → q.name 也變為 "Bob"(引用共享)
this 不能在 static 方法中使用(無當前對象)。