覆盖父类的List类型以避免在调用方法

时间:2015-09-01 09:53:12

标签: java generics inheritance

我有一个输入文件(text => TextFileImporter或xml => XmlFileImporter),其中包含具有不同结构的数据。 Definiton类中描述了一个结构,因此我的FileImporter对象包含Definition的多个实例。

TextFileImporter应保留List<TextDefinition>XmlFileImporter应保留List<XmlDefinition>

请查看示例代码:

// Parent classes
abstract class Definition {}

abstract class FileImporter {
  protected List<Definition> definitions;

  public FileImporter(List<Definition> definitions) {
    this.definitions = definitions;
  }

  public void doSomething() {
    // use 'definitions'
  }
}

// Text files
class TextDefinition extends Definition {
  public void copyLine() {}
}

class TextFileImporter extends FileImporter {
  // here should be clear that 'definitions' is of type List<TextDefinition>
  // to call 'copyLine()' on its items
}

// XML files
class XmlDefinition extends Definition {
  public void copyNode() {}
}

class XmlFileImporter extends FileImporter {
  // here should be clear that 'definitions' is of type List<XmlDefinition>
  // to call 'copyNode()' on its items
}

正如您在评论的基础上所看到的,我不确定如何处理这个问题。当然我首先需要构造函数。然后,我不想每次只调用方法时将definitions的每个项目转换为合适的子类。

我可以在这里合理使用仿制药吗?还是有另一种解决方案吗?

1 个答案:

答案 0 :(得分:3)

你必须介绍一些泛型。

// Parent classes
abstract class Definition {}

abstract class FileImporter<T extends Definition> {
  protected List<T> definitions;

  public FileImporter(List<T> definitions) {
    this.definitions = definitions;
  }

  public void doSomething() {
    // use 'definitions'
  }
}

// Text files
class TextDefinition extends Definition {
  public void copyLine() {}
}

class TextFileImporter extends FileImporter<TextDefinition> {
  // here should be clear that 'definitions' is of type List<TextDefinition>
  // to call 'copyLine()' on its items
}

// XML files
class XmlDefinition extends Definition {
  public void copyNode() {}
}

class XmlFileImporter extends FileImporter<XmlDefinition> {
  // here should be clear that 'definitions' is of type List<XmlDefinition>
  // to call 'copyNode()' on its items
}