Static abstract method workaround

我怕爱的太早我们不能终老 提交于 2019-12-23 04:21:20

问题


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 class and subclasses:

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?


回答1:


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


来源:https://stackoverflow.com/questions/21872406/static-abstract-method-workaround

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!