作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我最近开始学习 OOP,这让我很困惑。我想制作 super 汽车和电动或化石汽车作为其子类。
`abstract class Electric extends Car`.
问题是我只想创建 Private 或 Taxi 的实例。我该如何构建它,以便理想情况下允许我发表声明
Taxi cab1 = new Fossil()
我意识到这是一个答案显而易见的问题,但是在看了泛型和接口(interface)直到我眼睛发酸之后,挫败感一直在增长。
如果有人能提醒我如何做到这一点,我将不胜感激,因为我肯定我已经知道但后来忘记了。
最佳答案
你是这样想的吗?
汽车类别:
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);
}
}
关于java - parent - 汽车。子类: Electric or Fossil. child :私家车或出租车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41879660/
我是一名优秀的程序员,十分优秀!