Fruit 扩展了 HealthyFood,HealthyFood 扩展了 Food,但 Fruit 和 HealthyFood 都不能访问私有字符串名称;或私人 int cal;

Fruit extends HealthyFood which extends Food, yet neither Fruit nor HealthyFood can access private String name; or private int cal;

说明:

对于本练习,您将创建一个带有健康食品子class 的食品超级class。 HealthyFood 还将有一个 Fruit 子class。创建这些 classes 后,在 FoodTester class.

中测试结果

食物 class 将有两个实例变量,一个用于存储名称,一个用于存储卡路里。

食物也应该有两个访问器(getter 方法):

public String getName()
public int getCal()

HealthyFood class 将只有一个实例变量 group,它表示食物组并且应该具有以下访问器(getter 方法):

public String getGroup()

Fruit class 将有两个实例变量,一个布尔值指示符(如果水果是本地的)和颜色。访问器方法应该是:

public boolean isLocal()
public String getColor()

构造函数应遵循以下格式:

public Food (String foodName, int calories)
public HealthyFood(String foodName, int calories, String foodGroup)
public Fruit(String foodName, int calories, boolean isLocal, String foodColor)

最后,Food class 应该有一个 toString 打印: 名字有卡路里

例如:

Ice Cream has 200 calories

实际代码:

FoodTester.Java

public class FoodTester {
    public static void main(String[] args) {
        
    }
}

Fruit.java

public class Fruit extends HealthyFood {
    private boolean local;
    private String color;
    
    public Fruit(String foodName, int calories, boolean isLocal, String foodColor){
        super(name, calories, "Strings");
        local = isLocal;
        color = foodColor;
    }
    
    public boolean isLocal(){
        return local;
    }
    
    public String getColor(){
        return color;
    }
}

HealthyFood.java

public class HealthyFood extends Food {
    private String group;
    
    public HealthyFood(String foodName, int calories, String foodGroup){
        super(name, cal);
        group = foodGroup;
    }
    
    public String getGroup(){
        return group;
    }
}

Food.java

public class Food {
    private String name;
    private int cal;
    
    public Food(String foodName, int calories){
        name = foodName;
        cal = calories;
    }
    
    public String getName(){
        return name;
    }
    
    public int getCal(){
        return cal;
    }
    
    public String toString(){
        return name + " has " + cal + " calories";
    }
}

错误信息:

HealthyFood.java:6: error: name has private access in Food
        super(name, cal);
              ^
HealthyFood.java:6: error: cal has private access in Food
        super(name, cal);
                    ^
Fruit.java:7: error: name has private access in Food
        super(name, calories, "Strings");
              ^
3 errors

尝试这样修改:

public HealthyFood(String foodName, int calories, String foodGroup){
    super(foodName, calories);
    

public Fruit(String foodName, int calories, boolean isLocal, String foodColor){
       super(foodName, calories, "Strings");

您应该将 foodName 或 calories 作为超级构造函数的参数。