【问题标题】:Java Inheritance, Constructor and "super" [closed]Java 继承、构造函数和“超级”[关闭]
【发布时间】: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();

    }
}
  1. 问题:有没有什么好的方法可以解释为什么我需要 VehicleMain 中的构造函数?
  2. 问题:为什么要在构造函数中使用super()?
  3. 问题:在我的超类的方法drive()中,我应该使用私有字符串描述,还是方法getDescription()?

提前感谢您的帮助!

【问题讨论】:

  • 如果类中没有构造函数,您将如何创建 VehicleMain 的实例?您可以执行 new Vehicle() 但在这种情况下,java 将不知道有关 VehicleMain 的任何信息。如果你不想,你不必做超级。仅当您想初始化从父级继承的参数时才调用 super(params)。否则,您可以拥有自己的 VehicleMain 属性,而您的 Parent 也可以拥有自己的属性,但如果您不调用 super(properties),那么这些属性将为 null

标签: java oop inheritance constructor super


【解决方案1】:
  1. VehicleMain 扩展类Vehicle。所以你需要提供必要的参数来构造一个Vehicle给超类。

  2. 这与答案 1 密切相关。super() 调用是必需的,以便您可以使用必要的参数从 Vehicle 调用原始构造函数。

TBH VehicleMain 似乎完全没有必要。它没有理由扩展Vehicle,因为它没有在Vehicle 之上添加任何内容。您可以删除扩展和对VehicleMain 构造函数的调用,程序将运行相同。

【讨论】:

  • 感谢您的回答!
  • 我也刚刚意识到..我误解了作业,我以为是关于练习继承,结果不是..
  • 了解需求很重要! :-)
猜你喜欢
  • 2017-04-05
  • 2014-09-02
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 2020-08-07
  • 1970-01-01
相关资源
最近更新 更多