静态抽象方法解决方法

我想在abstract class创建一个abstract static method 。 我很清楚这个问题 ,这在Java中是不可能的。 什么是默认的解决方法/替代方式来思考问题/是否有一个选项可以为看似有效的示例(如下所示)执行此操作?

动物类和子类:

我有一个带有各种子类的基类Animal类。 我想强制所有子类能够从xml字符串创建一个对象。 对于这个,除了静态之外什么都没有意义呢? 例如:

 public void myMainFunction() { ArrayList animals = new ArrayList(); animals.add(Bird.createFromXML(birdXML)); animals.add(Dog.createFromXML(dogXML)); } public abstract class Animal { /** * Every animal subclass must be able to be created from XML when required * (Eg if there is a tag , bird would call its 'createFromXML' method */ public abstract static Animal createFromXML(String XML); } public class Bird extends Animal { @Override public static Bird createFromXML(String XML) { // Implementation of how a bird is created with XML } } public class Dog extends Animal { @Override public static Dog createFromXML(String XML) { // Implementation of how a dog is created with XML } } 

所以在我需要一个静态方法的情况下,我需要一种强制所有子类来实现这种静态方法的方法,有没有办法可以做到这一点?

您可以创建一个Factory来生成动物对象,下面是一个示例,为您提供一个开始:

 public void myMainFunction() { ArrayList animals = new ArrayList(); animals.add(AnimalFactory.createAnimal(Bird.class,birdXML)); animals.add(AnimalFactory.createAnimal(Dog.class,dogXML)); } public abstract class Animal { /** * Every animal subclass must be able to be created from XML when required * (Eg if there is a tag , bird would call its 'createFromXML' method */ public abstract Animal createFromXML(String XML); } public class Bird extends Animal { @Override public Bird createFromXML(String XML) { // Implementation of how a bird is created with XML } } public class Dog extends Animal { @Override public Dog createFromXML(String XML) { // Implementation of how a dog is created with XML } } public class AnimalFactory{ public static  Animal createAnimal(Class animalClass, String xml) { // Here check class and create instance appropriately and call createFromXml // and return the cat or dog } }