面向對象不僅是語法特性,更是一種建模思維。本文從不可變類設計、this 關鍵字、抽象封裝、關係建模、設計原則五個維度,深度探討 Java 面向對象的工程化實踐路徑。
public class Circle {
private int x = 0; // 實例字段
private int y = 0; // 實例字段
public void print() {
int x = 1; // 局部變量遮蔽字段
System.out.println("x = " + x); // 1
System.out.println("y = " + y); // 0
}
}
最佳實踐:避免局部變量與字段同名;必要時用 this.x 明確指代字段;字段儘量 private final。
this.field = paramthis(arg1, arg2) 必須在構造器首行obj.doSomething(this)static double k = 11;
static void setK(double k) {
// this.k = k; // 編譯錯誤:靜態方法無 this
Circle.k = k; // 必須用類名
}
// 過程式:數據與行為分離,難以擴展
public static double calcBMI(double weight, double height) { ... }
// 面向對象:數據行為封裝,支持擴展
public class Person {
private String name;
private int age;
private double weight;
private double height;
public Person(String name, int age, double weight, double height) { ... }
public double getBMI() { return weight / (height * height); }
public String getHealthAssessment() { ... } // 業務邏輯內聚
}
| 關係 | UML | 代碼體現 | 例子 |
|---|---|---|---|
| 組合 | 實心菱形 | 字段為對象,生命週期綁定 | Person → Heart (心臟) |
| 聚合 | 空心菱形 | 字段為對象,生命週期獨立 | Student ↔ Address (共享地址) |
| 關聯 | 實線箭頭 | 字段為對象引用 | Course → Student[] |
public class Student {
private String name;
public Student(String name) { this.name = name; }
public String getName() { return name; }
}
public class Course {
private String courseName;
private Student[] students = new Student[20];
private int count = 0;
public Course(String name) { this.courseName = name; }
public void addStudent(Student s) {
if (count < students.length) students[count++] = s;
}
public void dropStudent(Student s) { /* 移除邏輯 */ }
public Student getStudent(int i) { return students[i]; }
public int getNumberOfStudents() { return count; }
}
| 指標 | 高內聚表現 | 低耦合表現 |
|---|---|---|
| 代碼組織 | 相關邏輯集中在一個模塊 | 模塊間依賴少、接口簡單 |
| 修改影響 | 修改局限於單模塊 | 修改不波及其他模塊 |
| 復用性 | 功能單一易復用 | 依賴抽象而非具體實現 |
優秀的面向對象設計 = 清晰的領域建模 + 嚴格的封裝邊界 + 合理的關係分配 + 堅守的 SOLID 原則。從「寫代碼實現功能」進化到「設計結構應對變化」,是工程師成長的關鍵躍遷。