Instructions:
For this exercise, you are going to create a Food superclass with a HealthyFood subclass. The HealthyFood will also have a Fruit subclass. After creating these classes, test the results in the FoodTester class.
The Food class will have two instance variables, one to store the name and one to store the calories.
Food should have two accessor (getter methods) as well:
public String getName()
public int getCal()
The HealthyFood class will only have one instance variable, group, which represents the food group and should have the following accessor (getter method):
public String getGroup()
The Fruit class will have two instance variables, a boolean indicator if the fruit is local and the color. The accessor methods should be:
public boolean isLocal()
public String getColor()
Constructors should follow this format:
public Food (String foodName, int calories)
public HealthyFood(String foodName, int calories, String foodGroup)
public Fruit(String foodName, int calories, boolean isLocal, String foodColor)
Finally, the Food class should have a toString that prints: name has cal calories
For example:
Ice Cream has 200 calories
Actual code:
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";
}
}
Error messages:
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
Try to modify like this:
public HealthyFood(String foodName, int calories, String foodGroup){
super(foodName, calories);
and
public Fruit(String foodName, int calories, boolean isLocal, String foodColor){
super(foodName, calories, "Strings");
You should put foodName or calories as arguments for the super constructors.