【发布时间】:2014-03-19 07:21:18
【问题描述】:
我想在abstract class 中创建一个abstract static method。我从this question 很清楚,这在 Java 中是不可能的。什么是默认的解决方法/思考问题的替代方式/对于看似有效的示例(如下面的示例)是否可以选择执行此操作?
动物类和子类:
我有一个带有各种子类的基本 Animal 类。我想强制所有子类能够从 xml 字符串创建对象。为此,除了静态之外,它没有任何意义吗?例如:
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
}
}
所以如果我需要一个静态方法,并且我需要一种强制所有子类实现这个静态方法的方法,有没有办法可以做到这一点?
【问题讨论】:
-
查看抽象工厂和工厂模式。这里的摘要与Java中的关键字
abstract无关。
标签: java inheritance static abstract-class