静态抽象方法解决方法

时间:2014-02-19 06:05:19

标签: java inheritance static abstract-class

我想在abstract static method中创建abstract class。我很清楚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
    }
}

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

1 个答案:

答案 0 :(得分:2)

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

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
    }
}