將現實問題映射為程式概念,是編程入門關鍵躍遷。本節通過類組合演示如何建模幾何、電商、家譜、文件系統等領域。
String:不可變字串,內部 char[],提供豐富操作方法。Date:日期時間,內部 long 時間戳,new Date() 取當前時間。public class Point {
private double x, y;
public Point(double x, double y) { this.x = x; this.y = y; }
public double getX() { return x; }
public double getY() { return y; }
public double distance(Point p) {
return Math.hypot(x - p.getX(), y - p.getY());
}
}
public class Line {
private Point start, end;
public Line(Point start, Point end) { this.start = start; this.end = end; }
public double length() { return start.distance(end); }
}
記憶體佈局:Line 持有兩個 Point 引用,實際物件在堆中,引用在棧中。封裝內部細節,對外提供高層行為 (length())。

public class Product { String id, name, pictureUrl, description; double price; }
public class User { String name, password; }
public class OrderItem { Product product; int quantity; double computePrice() { return product.getPrice()*quantity; } }
public class Order {
String id; User user; OrderItem[] items; Date createTime;
String receiver, address, phone, status;
double computeTotalPrice() { /* 累加 items */ }
}
關係:Order → User (關聯),Order → OrderItem[] (組合/包含),OrderItem → Product (關聯)。
public class Person {
String name; Person father, mother; Person[] children;
public Person(String name) { this.name = name; }
}
// 使用:
Person laoma = new Person("老馬");
Person xiaoma = new Person("小馬");
xiaoma.setFather(laoma);
laoma.setChildren(new Person[]{xiaoma});
System.out.println(xiaoma.getFather().getName()); // 老馬
實例欄位可為 null,建構後再建立雙向關聯,記憶體形成圖結構。

public class MyFile { String name; Date createTime; int size; MyFolder parent; }
public class MyFolder {
String name; Date createTime; MyFolder parent;
MyFile[] files; MyFolder[] subFolders;
int totalSize() { /* 遞歸累加 files.size + subFolders.totalSize() */ }
}
MyFile 引用 MyFolder,MyFolder 引用 MyFile 與 MyFolder,構成樹結構。遞歸方法 totalSize() 自然表達「資料夾大小 = 檔案大小 + 子資料夾大小」。
Order 包含 OrderItem。Order 關聯 User。分解現實概念 → 定義類別 → 確定屬性/行為 → 建立類別組合關係,是物件導向建模核心思維。下節將探討繼承關係。
