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

Java 入門進階:面向對象編程核心概念與租車系統實戰練習

     編輯:Java 綜合教學

學習路線圖

  1. 類與對象:定義、構造、this、static、內部類
  2. 封裝:訪問修飾符、包管理、Getter/Setter、驗證
  3. 繼承:extends、方法重寫、super、final、Object 類
  4. 多態:向上/向下轉型、instanceof、抽象類、接口、UML

綜合練習:控制台租車系統

需求:展示車型 → 選擇車輛/數量/天數 → 輸出總載客、載貨、總金額。

領域模型

abstract class Car { abstract int rentPerDay(); }
interface CarryPeople { int capacity(); }
interface CarryGoods { int loadKg(); }

class SmallCar extends Car implements CarryPeople {
    public int rentPerDay() { return 100; }
    public int capacity() { return 4; }
}
class Bus extends Car implements CarryPeople {
    public int rentPerDay() { return 500; }
    public int capacity() { return 30; }
}
class Pickup extends Car implements CarryPeople, CarryGoods {
    public int rentPerDay() { return 200; }
    public int capacity() { return 4; }
    public int loadKg() { return 200; }
}
class Truck extends Car implements CarryGoods {
    public int rentPerDay() { return 500; }
    public int loadKg() { return 2000; }
}

主程序邏輯

Scanner sc = new Scanner(System.in);
List rented = new ArrayList<>();
// 交互選擇車型、數量、天數...
int totalRent = rented.stream().mapToInt(Car::rentPerDay).sum() * days;
int totalPeople = rented.stream().filter(c -> c instanceof CarryPeople)
                        .mapToInt(c -> ((CarryPeople)c).capacity()).sum();
int totalLoad = rented.stream().filter(c -> c instanceof CarryGoods)
                      .mapToInt(c -> ((CarryGoods)c).loadKg()).sum();
System.out.printf("總租金: %d 元, 載客: %d 人, 載貨: %d kg%n", totalRent, totalPeople, totalLoad);

運行效果

租車系統運行截圖

通過該練習可熟練掌握繼承、接口、多態、集合流式操作等核心技能。

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