英文:
cannot be resolved or is not a field in class inheritance
问题
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) {
Mammals cat = new Mammals();
Other snake = new Other();
Mammals frog = new Mammals();
Sea tuna = new Sea();
Mammals bear = new Mammals();
Sea eel = new Sea();
System.out.println(cat.name + " is " + cat.weight + " pounds, has " + cat.numberLegs + " legs, has " + cat.colorHair + " hair.");
}
}
Note: I've corrected the capitalization of class names to follow Java conventions (classes start with uppercase letters), and I've adjusted the variable assignments to match the class structures. The inheritance hierarchy and variable assignments should now work correctly.
英文:
Simple java assignment: Create a class called Animal. Give it one data item, weight.
Create two subclasses Land and Sea; give the land animal nuberLegs;
give the sea animal number fins.
Create two subclasses under Land, Mammals and Other, Give Mammals colorHair;
give Other hasScales.
Now create a cat, snake, frog, tuna, bear, and eel.
Print out the attributes for each animal you created.
I am currently getting errors for cat.numberLegs, cat.numberFins, cat.colorHair, and cat.hasScales saying that they cannot be resolved or is not a field. I am also pretty sure I am doing the inheritance part wrong, but I'm not sure how to fix it.
Here's my code for it:
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.");
}
}
I edited the code in response to comments and answers, but it is still giving me the same error.
答案1
得分: 1
你需要将你的实例声明为其中一个子类。
例如:
动物 猫 = 新的哺乳动物();
你已经将猫声明为动物,所以它只有重量和名字这两个属性。
猫应该是哺乳动物,这意味着它会从动物继承重量和名字,
从陆地继承腿的数量,从哺乳动物继承毛发的颜色。它仍然不会有鳍或鳞片,因为它不是海洋生物或其他类型。
英文:
You need to declare your instances as being one of the subclasses.
For example
animal cat = new mammals();
You have declared cat as an animal, so the only attributes it has are weight and name.
cat should be a mammals, that means it will have weight and name from animal,
numberLegs from land and colorHair from mammal. It still will not have fins or scales because it is not sea or other.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论