Java 應用程式 = 無數個類別的組合。理解類別結構是入門第一步。
package com.csst.vo;
public class Customer {
// 1. 資料成員 (私有封裝)
private String custName;
private String password;
private Integer age;
// 2. 建構子 (多載)
public Customer() {} // 無參建構子
public Customer(String custName, String password) {
this.custName = custName;
this.password = password;
}
public Customer(String custName, String password, Integer age) {
this(custName, password); // 呼叫另一建構子
this.age = age;
}
// 3. 方法成員 (Getter/Setter)
public String getCustName() { return custName; }
public void setCustName(String custName) { this.custName = custName; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
}
private 封裝,對外僅透過方法存取。int) 或參考型別 (String, Integer)。null/0/false)。void 都不寫)。new Customer("Tom", "123") 配置初始狀態。this(...) 鏈式呼叫其他建構子,減少重複程式碼。public 提供對外服務。void。getXxx, setXxx, calculateTotal)。型別 參數名。Customer c1 = new Customer(); // 呼叫無參建構子
Customer c2 = new Customer("Alice", "pwd123"); // 呼叫兩參建構子
Customer c3 = new Customer("Bob", "pwd456", 25); // 呼叫三參建構子
c1.setCustName("Charlie");
System.out.println(c2.getCustName()); // Alice
Stack (main) Heap
┌──────────────────┐ ┌──────────────────────┐
│ c1 ──────────────┼──────────►│ Customer object │
│ c2 ──────────────┼──────────►│ custName = "Alice" │
│ c3 ──────────────┼──────────►│ password = "pwd123" │
└──────────────────┘ │ age = null │
└──────────────────────┘
| 錯誤 | 說明 |
|---|---|
建構子寫了 void | 建構子不能有回傳型別 |
忘記 this. 導致參數遮蔽欄位 | this.custName = custName; |
直接存取 private 欄位 | 必須透過 getter/setter |
| 類別名稱不符合 PascalCase | 類別名首字母大寫:Customer 非 customer |
「資料成員描述是什麼,建構子決定如何出生,方法成員定義能做什麼」。掌握這三大組成,並養成封裝與命名好習慣,即踏入 Java 物件導向大門。