我有一个超类 Animal,它有两个子类 Cat 和 Dog。狗和猫都需要有特定的说话和移动方法。以下是实现此目的的两种选择:
- Animal 会有两个抽象方法 move() 和 speak();Dog、Cat 和 Dog 分别覆盖这两个方法,因此它们是特定于它们的。
- 我可以有一个具有通用动物方法 move() 和 speak() 的接口,两个子类实现这些方法,因此它们再次特定于它们。
这些方法中的一种是否比另一种更合适?我意识到如果我有一个动物的 ArrayList,我会写:
ArrayList Animal<allAnimals> = new ArrayList <Animal>():
allAnimals.add(new Dog());
allAnimals.add(new Cat());
//If I override the methods, I can simply go:
for (Animal a: allAnimals) a.move();
//Where as if I implemented the methods, I would not need be able to do this. I would need to cast the animal as its specific animal. e.g. If I knew the animal was a dog.
Dog aDog= (Dog) a;
a.move();
因此,根据使用的情况,覆盖和实施可能具有某些优点和缺点。其他人可以详细说明吗?