【发布时间】:2020-10-21 10:46:12
【问题描述】:
我目前正在学习 Java,我的任务是了解 OOP。 我了解类的理论,但我对实现有疑问。
以下代码为例:
class Vehicle {
private String engine;
private int wheels;
private int seats;
private int fuelTank;
private String lights;
public Vehicle() {
this.engine = "petrol";
this.wheels = 4;
this.seats = 4;
this.fuelTank = 35;
this.lights = "LED";
}
public Vehicle(String engine, int wheels, int seats, int fuelTank, String lights) {
this.engine = engine;
this.wheels = wheels;
this.seats = seats;
this.fuelTank = fuelTank;
this.lights = lights;
}
public String getEngine() {
return engine;
}
public int getWheels() {
return wheels;
}
public int getSeats() {
return seats;
}
public int getFueTank() {
return fuelTank;
}
public String getLights() {
return lights;
}
}
class Car extends Vehicle {
private String steering;
private String musicSystem;
private String airConditioner;
private String fridge;
private String entertainmentSystem;
public Car() {
super();
this.steering = "Power Steering";
}
public Car(String steering, String engine, int wheels, int seats, int fueTank, String lights) {
super(engine, wheels, seats, fueTank, lights);
this.steering = steering;
}
public String getSteering() {
return steering;
}
}
class Demo {
public static void main(String[] args) {
Car car = new Car("Power steering", "deisel", 4, 4, 40, "LED");
System.out.println("Steering: " + car.getSteering());
System.out.println("Engine type: " + car.getEngine());
System.out.println("Number of seats: " + car.getSeats());
System.out.println("Fuel tank capacity: " + car.getFueTank());
System.out.println("Head lamp type: " + car.getLights());
System.out.println("Number of wheels: " + car.getWheels());
}
}
我在这里了解到,您可以使用默认构造函数或参数化构造函数来创建 Vehicle 对象。我也可以对从Vehicle 扩展的Car 对象执行相同的操作。我知道通过在默认构造函数中使用super(),它将使用Vehicle 中的默认构造函数以及Car 对象转向变量默认值。与使用super(args) 的参数化构造函数相同。
我在理解如何在每个扩展级别的车辆中对车轮进行硬编码时遇到问题。
为了解释更多,我不想在创建Car 对象时在构造函数中包含轮子。我希望它默认为 4。此外,如果我要创建一个从 Vehicle 扩展的 Bike 对象,我希望轮子变量默认为 2。
【问题讨论】: