【发布时间】:2021-11-15 23:56:00
【问题描述】:
大家好,我最近开始学习 Java 中的 OOP,我只是有几个问题,我将使用我(可能写得不好)的代码来演示。
让我先介绍一下我的超类,Vehicle:
public class Vehicle {
private String description;
private double speed;
private double tankLevel;
public Vehicle(String description, double speed, double tankLevel) {
this.description = description;
this.speed = speed;
this.tankLevel = tankLevel;
}
public Vehicle() {
}
public Vehicle(String description, double speed) {
this.description = description;
this.speed = speed;
}
public void drive() {
if(getTankLevel() != 0) {
if(getSpeed() != 0) {
System.out.println("Your " + getDescription() + " is driving");
}
else {
System.out.println("You have enough fuel but your "+ getDescription() +" isn't running");
}
}
else {
System.out.println("Tanklevel too low!");
}
}
public double getTankLevel() {
return tankLevel;
}
public double getSpeed() {
return speed;
}
public String getDescription() {
return description;
}
}
现在这是我的第一个问题的子类 VehicleMain:
public class VehicleMain extends Vehicle {
public VehicleMain(String description, double speed, double tankLevel) {
super(description, speed, tankLevel);
}
public static void main(String[] args) {
Vehicle car = new Vehicle("car", 20, 5);
car.drive();
}
}
- 问题:有没有什么好的方法可以解释为什么我需要 VehicleMain 中的构造函数?
- 问题:为什么要在构造函数中使用super()?
- 问题:在我的超类的方法drive()中,我应该使用私有字符串描述,还是方法getDescription()?
提前感谢您的帮助!
【问题讨论】:
-
如果类中没有构造函数,您将如何创建 VehicleMain 的实例?您可以执行 new Vehicle() 但在这种情况下,java 将不知道有关 VehicleMain 的任何信息。如果你不想,你不必做超级。仅当您想初始化从父级继承的参数时才调用 super(params)。否则,您可以拥有自己的 VehicleMain 属性,而您的 Parent 也可以拥有自己的属性,但如果您不调用 super(properties),那么这些属性将为 null
标签: java oop inheritance constructor super