java - 子类中的构造函数,只有超类的部分参数
问题描述
嗨,我是 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;
}
}
解决方案
你可能
- 将常量fuelType传递给构造函数
- 在 Vehicle 中创建另一个构造函数并将fuelType 初始化为某个常量值。
但是,在这种情况下,实例化 Car 对象而不指定fuelType 没有多大意义。
推荐阅读
- swift - swift SceneKit 对象为空
- python - 如何过滤列和绘制一堆文件
- azure - 如何在 ARM 模板中获取 AzureAD 用户 principalId
- android - 当应用程序获得焦点时,何时检查 Android API 29 中的剪贴板内容?
- android - MPAndroidChart - 比例线图
- javascript - NullInjectorError:StaticInjectorError(i)[s -> e]:Angular 8
- excel - 为什么 Excel 2010 VBA 用户窗体文本框字体会根据框架的大小而变化?
- java - @Version 注释导致“对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例”异常
- r - R 中的函数、For 循环和条件
- tkinter - Tkinter 对话框问题