【问题标题】:Static abstract method workaround静态抽象方法解决方法
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这似乎是一个有效的解决方法。不过,您添加的那段代码似乎是错误的。不应该是public &lt;T extends Animal&gt; static Animal createAnimal(Class&lt;T&gt; animalClass, String XML)吗?
  • 是的,可能是因为我只是在这里写它只是为了给你一个想法,而不是运行这个。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
相关资源
最近更新 更多