我正在学习java和多态。我正在使用 java 的书籍开头。我试图用它们做实验。我了解到您可以调用的方法取决于引用对象。所以我创建了这段代码
package animals;
public class AnimalstestDrive {
static public Animals[] myZoo = new Animals[5];
static int zooCounter = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Dog 1 test");
Dog myDog = new Dog();
myDog.eatFood();
myDog.sleep();
myDog.makeNoises();
System.out.println("Dog 2 test");
Animals myNewDog = new Dog();
myNewDog.eatFood();
myNewDog.makeNoises();
//Set animals array
System.out.println("Dog 3 test");
Animals zooDog = new Dog();
addAnimals(zooDog);
Cat zooCat = new Cat();
addAnimals(zooCat);
myZoo[0].makeNoises();
}
public static void addAnimals(Animals a){
if ( zooCounter < 5 ){
myZoo[zooCounter] = a;
zooCounter++;
}
else
System.out.println("Zoo is full");
}
}
引起我问题的一件事是控制台上没有显示“Dog 3 test”。它工作正常,直到狗 2,但狗 3 不工作。
这是我的动物课
package animals;
public abstract class Animals {
private String Name;
private int Size; //Size on the scale 1 to 10
public void eatFood(){
System.out.println("I am eating food");
}
public void sleep(){
System.out.println("I am sleeping now");
}
abstract public void makeNoises();
}