java – 对Sub Sub Class的继承
发布时间:2020-12-15 04:23:27 所属栏目:Java 来源:网络整理
导读:我正在研究一个赋值有一个关于子类继承的问题,实际上是一个子类的子类的问题.我有三个类,Fruit(主类),Apple(水果的子类,也是抽象的),Macintosh(苹果的子类). Fruit包含一系列构造函数方法,Apple是抽象的并且包含一个方法,而MacIntosh包含对超类(Fruit)的构造
我正在研究一个赋值有一个关于子类继承的问题,实际上是一个子类的子类的问题.我有三个类,Fruit(主类),Apple(水果的子类,也是抽象的),Macintosh(苹果的子类). Fruit包含一系列构造函数方法,Apple是抽象的并且包含一个方法,而MacIntosh包含对超类(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,color,0d); } protected Fruit(String name,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(),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时,程序可以工作,但是,似乎两者之间不能有类.如果有人能解释这将是伟大的. 解决方法
构造函数不是继承的,所以即使Apple扩展了Fruit,构建Apple的唯一方法是调用Apple提供的构造函数之一(在这种情况下是默认的无参数构造函数).当您的Macintosh扩展Apple时,它必须使用Apple提供的构造函数.
对于您的代码,您必须至少向Apple提供以下构造函数 Apple(String name,double weight) { super(name,weight); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |