首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

程式設計思維邏輯(14):類的組合與現實概念映射——從幾何圖形到電商訂單、家譜與文件系統

     編輯:Java 綜合教學

程式設計思維邏輯(14):類的組合與現實概念映射

將現實問題映射為程式概念,是編程入門關鍵躍遷。本節通過類組合演示如何建模幾何、電商、家譜、文件系統等領域。

基礎類別:String 與 Date

  • String:不可變字串,內部 char[],提供豐富操作方法。
  • Date:日期時間,內部 long 時間戳,new Date() 取當前時間。

幾何領域:Point → Line

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())。

Line 記憶體佈局

電商領域:Product / User / Order / OrderItem

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 (關聯)。

家譜領域:Person 遞歸引用

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,建構後再建立雙向關聯,記憶體形成圖結構。

Person 記憶體圖

文件系統:MyFile / MyFolder 互相引用

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。

小結

分解現實概念 → 定義類別 → 確定屬性/行為 → 建立類別組合關係,是物件導向建模核心思維。下節將探討繼承關係。

微信公眾號二維碼

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved