实际上,从超类执行此操作不是一个好方法,因为每个子类的行为都不同。
为了确保您实际上在调用适当的
move方法,请
Animal从超类更改为接口。然后,当您调用该
move方法时,您将能够确保为所需的对象调用适当的move方法。
如果要保留公共字段,则可以定义一个抽象类
Animalbase,并要求所有动物都以此为基础,但是每个实现都需要实现该
Animal接口。
例:
public abstract class Animalbase { private String name; private int age; private boolean gender; // getters and setters for the above are good to have here}public interface Animal { public void move(); public void eat(); public void sleep();}// The below won't compile because the contract for the interface changed.// You'll have to implement eat and sleep for each object.public class Reptiles extends Animalbase implements Animal { public void move() { System.out.println("Slither!"); }}public class Birds extends Animalbase implements Animal { public void move() { System.out.println("Flap flap!"); }}public class Amphibians extends Animalbase implements Animal { public void move() { System.out.println("Some sort of moving sound..."); }}// in some method, you'll be calling the belowList<Animal> animalList = new ArrayList<>();animalList.add(new Reptiles());animalList.add(new Amphibians());animalList.add(new Birds());// call your method without fear of it being genericfor(Animal a : animalList) { a.move();}


