首页 > 解决方案 > 子类中的构造函数,只有超类的部分参数

问题描述

嗨,我是 java 的初学者,我正在研究课程,我试图让我的头脑围绕继承。如果子类中的参数与超类的参数匹配,然后将子类构造函数中的剩余参数分配给该子类的实例变量,我将了解如何使用 super 从超类引用构造函数。
我感到困惑的是,如果我想创建一个子类的对象,其中构造函数只有部分参数,但该子类仍然可以引用超类的方法来返回其名称。下面的示例无法编译,因为它期望在 Car 的构造函数中的两个字符串之上输入 String。我误解了什么吗?

public class Vehicle{
    private String fuelType;

    public Vehicle(String fuelType){
        this.fuelType = fuelType;
    }
        public String getType(){
        return this.fuelType;
    }
}
public class Car extends Vehicle{
    private String make;
    private String model;

    public Car (String make, String model){
        this.make = make;
        this.model = model;
    }   
}

标签: javainheritanceconstructor

解决方案


你可能

  1. 将常量fuelType传递给构造函数
  2. 在 Vehicle 中创建另一个构造函数并将fuelType 初始化为某个常量值。

但是,在这种情况下,实例化 Car 对象而不指定fuelType 没有多大意义。


推荐阅读