你在想這樣的事嗎?
車類:
public class Car{
private int yearOfManufacture;
private String brand;
private String model;
private Engine engine;
public Car(String pBrand, String pModel, int pYearOfManufacture, Engine pEngine){
this.yearOfManufacture = pYearOfManufacture;
this.brand = pBrand;
this.model = pModel;
this.engine = pEngine;
}
}
引擎類:
public class Engine {
private int power;
private int emission;
public Engine(int power, int emission) {
this.power = power;
this.emission = emission;
}
}
IC引擎類:
public class ICEngine extends Engine {
private int numOfValves;
public ICEngine(int power, int emission, int numOfValves) {
super(int power, int emission);
this.numOfValves = numOfValves;
}
}
電動引擎類:
public class ElectricEngine extends Engine {
private int wattage;
public ICEngine(int power, int emission, int wattage) {
super(int power, int emission);
this.wattage = wattage;
}
}
出租車等級:
public class Taxi extends Car{
private String driverName;
public Taxi(String driverName, String pBrand, String pModel, int pYearOfManufacture, Engine engine){
super(pBrand, pModel, pYearOfManufacture, engine);
this.driverName = driverName;
}
}
私家車類:
public class PrivateCar extends Car {
private String ownerName;
public PrivateCar(String ownerName, String pBrand, String pModel, int pYearOfManufacture, Engine engine) {
super(pBrand, pModel, pYearOfManufacture, engine);
this.ownerName = ownerName;
}
}
消費應用類:
public class MyApp {
public static void main(String[] args) {
Engine eEngine1 = new ElectricEngine(100, 10, 10000);
Car myElectricTaxi = new Taxi("Driver1", "Honda", "Accord", 2013, eEngine1);
Engine icEngine1 = new ICEngine(100, 10, 6);
Car myICTaxi = new Taxi("Driver2", "Honda", "Accord", 2013, icEngine1);
Engine eEngine2 = new ElectricEngine(100, 10, 10000);
Car myElectricPrivateCar = new PrivateCar("Owner1", "Honda", "Accord", 2013, eEngine2);
Engine icEngine2 = new ICEngine(100, 10, 4);
Car myICPrivateCar = new PrivateCar("Owner2", "Honda", "Accord", 2013, icEngine2);
}
}
之前制定你的類層次結構,還明確你想要這些對象爲* *做什麼,因爲這會決定什麼可以使意義,因爲一個接口或抽象類,以及它們的關係應該是什麼。 例如,Taxi有不同於Private的方法嗎? – Lagerbaer
好點。私人和出租車將有一些他們不分享的方法,而電動出租車則需要繼承Electric的所有方法,然後繼承Car。出租車也可以是化石,在這種情況下,它將需要繼承所有化石方法,而不是電子方法。 Car和Fossil的常用方法將在Car中找到。 – user2005142
您可能想要將引擎類型分成單獨的類並用它來組合自定義類型,例如'出租車cab1 =新出租車(新ElectricMotor());'。 – shmosel