【发布时间】:2022-01-25 04:17:46
【问题描述】:
我在运行这个在 java 中测试继承的程序时遇到问题。我做了两个类,一个应该是父类的 Drink 类,一个应该是子类的 tea 类。我创建了一个构造函数,它使用 super() 调用父构造函数,以创建一个新的茶对象。但是,编译器告诉我,我发送的参数之一 (caloriesPerOunce) 的字段不可见。尽管我不需要将参数包含在 Tea() 的构造函数中,但我确实在稍后的块中声明并实例化了它。这是我的代码的问题,还是因为我使用的是 Eclipse IDE,我应该更改设置?
public class Drink {
private String name;
private double quantity;
private int caloriesPerOunce;
public Drink(String name, double quantity, int caloriesPerOunce)
{
this.name = name;
this.quantity = quantity;
this.caloriesPerOunce = caloriesPerOunce;
}
public class Tea extends Drink{
private boolean isSweet;
public Tea(String name, double quantity, boolean isSweet)
{
super(name, quantity, caloriesPerOunce); //here it tells me that the field Drink.caloriesPerOunce is not visble
int caloriesPerOunce = 100;
this.isSweet = isSweet;
}
【问题讨论】:
-
super(name, quantity, caloriesPerOunce);在您的具体情况下应该实现什么?caloriesPerOunce应该被茶所含的卡路里代替,因为在Tea中没有定义这样的变量
标签: java inheritance