java - 无法解析或不是类继承中的字段
问题描述
简单的 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.");
}
}
我编辑了代码以响应评论和答案,但它仍然给我同样的错误。
解决方案
您需要将您的实例声明为子类之一。
例如动物猫=新哺乳动物();
您已将 cat 声明为动物,因此它的唯一属性是重量和名称。
cat 应该是哺乳动物,这意味着它的重量和名称来自动物,numberLegs 来自陆地,colorHair 来自哺乳动物。它仍然没有鳍或鳞片,因为它不是海或其他。
推荐阅读
- c# - 将来自 Unity 的流式数据保存在 csv 文件中
- python - 在 Pandas 中,使用由列表列表过滤的数据创建一个新的数据框
- sql - 用户创建循环中 \ 和 GO 附近的语法不正确
- javascript - Mapbox GL JS 画布在 Bootstrap 模式中无法正确显示
- ruby - 比较符号(小于、小于或等于等)
- javascript - 检测何时使用 ember 更改了套接字 io 连接
- html - Bootstrap 4 图像卡片覆盖卡片文本
- php - 将变量写入工作表 PHP
- fabricjs - Fabric.js 撤消重做功能一次导致 2 个步骤
- css - 我的移动菜单被页面内容隐藏