我想在abstract class
中創建一個abstract static method
。我很清楚從this question這是不可能在Java中。什麼是默認的解決方法/思考問題的替代方式/是否可以選擇這樣做看似有效的示例(如下所示)?靜態抽象方法解決方法
動物類和子類:
我有一個基類Animal
與各子類。我想強制所有的子類能夠從一個XML字符串創建一個對象。對於這一點,除靜態以外沒有任何意義嗎? 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
}
}
所以在我需要一個靜態方法,我需要迫使所有子類有這個靜態方法的實現方式的情況下,是有辦法,我能做到這一點?
查找到抽象工廠和工廠模式。在這裏抽象與Java中關鍵字'abstract'無關。 –