[英]Programmatic return type or casting for getting, and calling methods of, a child with a generic parent
[英]Overwriting the List type of the parent class to avoid casting when calling methods
我有一個輸入文件(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
每個項目都definitions
轉換為合適的子類,僅是為了調用方法。
我可以在這里合理使用泛型嗎? 還是有其他解決方案?
您必須引入一些泛型。
// 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.