首页 > 解决方案 > 无法解析或不是类继承中的字段

问题描述

简单的 java 赋值:创建一个名为 Animal 的类。给它一个数据项,重量。创建两个子类 Land 和 Sea;给陆地动物 nuberLegs;给海洋动物编号鳍。在 Land、Mammals 和 Other 下创建两个子类,Give Mammals colorHair;给其他hasScales。现在创建一只猫、蛇、青蛙、金枪鱼、熊和鳗鱼。打印出您创建的每只动物的属性。

我目前收到 cat.numberLegs、cat.numberFins、cat.colorHair 和 cat.hasScales 的错误,指出它们无法解析或不是字段。我也很确定我做错了继承部分,但我不知道如何解决它。

这是我的代码:

class animal {
    String name = "cat";
    Number weight = 9;
}
class land extends animal {
    Number numberLegs = 4;
}
class mammals extends land {
    String colorHair = "brown";
}
class other extends land {
    String hasScales = "no";
}
class sea extends animal {
    Number numberFins = 4;
}
public class animalClasses {

    public static void main(String[] args) {
        animal cat = new mammals();
        animal snake = new other();
        animal frog = new mammals();
        animal tuna = new sea();
        animal bear = new mammals();
        animal eel = new sea();
        System.out.println(cat.name + " is " + cat.weight + " pounds, has " + cat.numberLegs + " legs, has " + cat.colorHair + " hair.");
    }

}

我编辑了代码以响应评论和答案,但它仍然给我同样的错误。

标签: java

解决方案


您需要将您的实例声明为子类之一。

例如动物猫=新哺乳动物();

您已将 cat 声明为动物,因此它的唯一属性是重量和名称。

cat 应该是哺乳动物,这意味着它的重量和名称来自动物,numberLegs 来自陆地,colorHair 来自哺乳动物。它仍然没有鳍或鳞片,因为它不是海或其他。


推荐阅读