我练习多态性和继承,我创建了一个类(Animals)来设置动物的名字,然后我创建了一个子类(Cat)来设置它发出的声音,最喜欢的玩具......所有这些。我尝试在单独的课程(测试)中对其进行测试以打印出“猫喜欢 Moew,它最喜欢的玩具是纱线”,但除非我在测试课程中扩展 Cat,否则它不起作用。
这是我的代码。
Animals.java
public class Animals {
protected static String name;
public Animals() {
}
public Animals(String name) {
this.name = name;
}
public String setName(String newName) {
return this.name = newName;
}
public String getName() {
return name = name;
}
public static void animMove() {
System.out.println(name + " likes to walk");
}
}
Cat.java
public class Cat extends Animals {
public static String sound;
public static String favToy;
public String getSound(String sound) {
return this.sound = sound;
}
public String getToy(String favToy) {
return this.favToy = favToy;
}
public Cat() {
}
public Cat(String name, String sound, String favToy) {
super(name);
this.sound = sound;
this.favToy = favToy;
}
}
test.java
public class test{
public static void main(String[] args) {
Animals anim = new Animals();
Cat cat = new Cat("Cat", "moew", "Yarn ball");
System.out.println(anim.getName() + " Likes to " + cat.getSound(sound)
+ ", its favourite toy is a " + cat.getToy(favToy));
}
}
如果我将 Cat 扩展到测试类,一切正常,但是当我不这样做时,声音和 favToy 之类的变量都不起作用。如果不将任何内容扩展到测试类,我将如何做到这一点
泛舟湖上清波郎朗
呼啦一阵风
相关分类