【发布时间】:2014-11-04 15:43:12
【问题描述】:
我正在处理一个关于子类继承的问题,实际上是子类的子类的问题。我有三个类,水果(主类),苹果(水果的子类,也是抽象的),Macintosh(苹果的子类)。 Fruit 包含一系列构造函数方法,Apple 是抽象的,包含一个方法,MacIntosh 包含对超类(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);
}
}
当我运行程序时,我收到以下错误:
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
我明白错误在说什么我只是对为什么没有将继承从 Fruit 传递到 Apple 到 Macintosh 感到困惑。但是,当我从 Macintosh 类扩展 Fruit 时,程序可以工作,但是,两者之间似乎没有一个类。如果有人能解释这一点,那就太好了。
【问题讨论】:
-
super(..)在构造函数中做了什么? -
我相信它会根据超类构造函数设置默认值
-
设置默认值是什么意思?这种情况下的超类构造函数是什么?
-
它正在构建一个名为 macintosh 的苹果。我更指的是 macinotsh 苹果的构造函数特征。构造函数在水果类中,但我现在明白这些不是继承的。
标签: java inheritance