我很确定在 java 中你不能将一个类设为静态,除非它是一个内部类;但这超出了您的问题的重点。
您必须强制转换,因为您无法匹配方法的正确原型private void catAttack(Cat other)
或private void catAttack(Dog other)
与catAttach(Animal other)
.
为了解决这个问题,您对超类或接口进行编程。
通常以这种方式完成:
public interface Animal {
public void attack(Animal other);
}
public class Cat implements Animal {
public void attack(Animal other) {
/* TODO: implement attack method */
}
}
public class Dog implements Animal {
public void attack(Animal other) {
/* TODO: implement attack method */
}
}
如果你仔细想想,这种方法是有道理的。ACat
在这种情况下,有其自身的攻击性质。您可以执行以下操作:
public class Cat implements Animal {
public void attack(Animal other) {
if (this.equals(other)) {
System.out.println("The Cat won't fight itself.");
} elsif (other instanceof Cat) {
System.out.println("Cats are friendly to one another, so the Cat forfeits the fight!");
} elsif (other instanceof Dog) {
System.out.println("Cats hate Dogs, so the Cat viciously attacks the Dog!");
} else {
System.out.println("The Cat seems to be unamused by the other animal, and walks away...");
}
}
你可以让它变得更复杂:
public class MountainLion extends Cat {
@Override
public void attack(Animal other) {
System.out.println("Mountain Lions do not like to be challenged and will strike down any predator with the fire inside their heart!");
}
}
但是在使用它们的类中,您只需遵循接口模式,如下所示:
public class AnimalKingdom {
public static void main(final String[] args) {
Animal cat = new Cat(); // could be read in from something like Spring using context.getBean("catObject", Animal.class);
Animal dog = new Dog(); // same as above...
Animal randomAnimalType = new MountainLion(); // same as above...
cat.attack(cat);
cat.attack(dog);
cat.attack(randomAnimalType);
dog.attack(cat);
dog.attack(dog);
dog.attack(randomAnimalType);
randomAnimalType.attack(cat);
randomAnimalType.attack(dog);
randomAnimalType.attack(randomAnimalType); // this doesn't use super, doesn't check if the animal is the same instance...
}
}
关键是,如果我现在可以创建 AnimalKingdom 的行为而不用担心它是什么类型的 Animal,那么它就是一个 Animal(所以它遵循 Animal 接口)。如果我使用某种框架(例如 Spring),我可以动态注入基于一些外部配置文件运行的内容,以创建许多可能的场景,而无需复制和粘贴或重新编写代码。
希望这会有所帮助。
谢谢