Subclass inheritance
I am working on an assignment, asking a question about subclass inheritance, actually the problem is with the subclass subclass. I have three classes: Fruit (main class), Apple (subclass of fruits, also abstract), Macintosh (subclass of apple). Fruits contain a number of constructor methods, Apple is abstract and contains one method, and MacIntosh contains a constructor call for the superclass (Fruit).
Fruit.java
public abstract class Fruit extends Object {
// The name of the fruit
protected String mName;
// Number of calories
protected int mCalories;
// Color of the fruit
protected Color mColor;
// Weight of the fruit, in pounds
protected double mWeight;
protected Fruit() {
this("Apple");
// Default fruit
}
protected Fruit(String name) {
this(name, 0);
}
protected Fruit(String name, int calories) {
this(name, calories, null);
}
protected Fruit(String name, int calories, Color color) {
this(name, calories, color, 0d);
}
protected Fruit(String name, int calories, Color color, double weight) {
this.mName = name;
this.mCalories = calories;
this.mColor = color;
this.mWeight = weight;
}
Apple.java
abstract class Apple extends Fruit {
abstract void bite();
}
Macintosh.java
public class Macintosh extends Apple {
public Macintosh() {
super(Macintosh.class.getSimpleName(), 200, new Red(), 0.14d);
}
void bite() {
setWeight(getWeight() - 0.01d);
}
}
When I run the program, I get the following error:
super(Macintosh.class.getSimpleName(), 200, new Red(), 0.14d);
^
required: no arguments
found: String,int,Red,double
reason: actual and formal argument lists differ in length
1 error
I understand what the error is saying. I am just confused as to why inheritance is not passed from Fruit to Apple to Macintosh. When I extend Fruit from the Macintosh class, the program works, however, there seems to be no class in between. If anyone could explain this it would be great.
source to share
Constructors are not inherited, so while Apple extends Fruit, the only way to build Apple is to name one of the constructors provided by Apple (in this case, the default no-arg constructor). When your Macintosh extends Apple, it should use the constructor provided by Apple.
For your code, you need at least provide the following Apple constructor
Apple(String name, int calories, Color color, double weight) {
super(name, calories, color, weight);
}
source to share
you call the apple constructor with 4 arguments, but in the apple class you don't have a constructor for this code:
super(Macintosh.class.getSimpleName(), 200, new Red(), 0.14d);
you need to define an apple constructor with four parameters:
Apple(String name, int calories, Color color, double weight) {
super(name, calories, color, weight);
}
source to share