问题描述
我想在抽象类
中创建一个静态抽象方法
。我从清楚地知道在Java中。默认的解决方法是什么/解决问题的替代方式/是否可以对看似有效的示例执行此操作(类似于下面的示例)?
I would like to create a abstract static method
in an abstract class
. I am well aware from this question that this is not possible in Java. What is the default workaround / alternative way of thinking of the problem / is there an option for doing this for seemingly valid examples (Like the one below)?
动物类和子类:
我有一个基本的 Animal
类,其中包含各种子类。我想强制所有子类能够从xml字符串创建对象。为此,除了静态之外什么都没有意义吗?例如:
I have a base Animal
class with various subclasses. I want to force all subclasses to be able to create an object from an xml string. For this, it makes no sense for anything but static does it? E.g:
public void myMainFunction() {
ArrayList<Animal> animals = new ArrayList<Animal>();
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
* (E.g. if there is a tag <bird></bird>, 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
}
}
创建的,因此在需要静态方法,并且我需要一种强制所有子类都具有此静态方法的实现的方法,有没有办法做到这一点?
So in cases where I need a static method, and I need a way of forcing all subclasses to have an implementation of this static method, is there a way I can do that?
推荐答案
您可以创建一个生产动物物体的工厂,下面是一个示例,为您提供了一个起点:
You can create a Factory to produce the animal objects, Below is a sample to give you a start:
public void myMainFunction() {
ArrayList<Animal> animals = new ArrayList<Animal>();
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
* (E.g. if there is a tag <bird></bird>, 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 <T extends Animal> Animal createAnimal(Class<T> animalClass, String xml) {
// Here check class and create instance appropriately and call createFromXml
// and return the cat or dog
}
}
这篇关于静态抽象方法解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!