需求:展示車型 → 選擇車輛/數量/天數 → 輸出總載客、載貨、總金額。
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); Listrented = 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);

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