我有一个具有以下属性的 A 类:
class A {
String a;
String b;
.....
List<C> myList;
}
我想要一个类 Aext 来扩展 A 并“扩展”myList 属性,意思是:
class Aext extends A {
String x;
.....
List<Cext> myList;
....
}
哪里:
class Cext extends C {
......
}
但是我不能在子类中拥有与父类(super class)同名的成员,即:myList。姓名不得更改。我想要一个“扩展的”myList,它具有 C 的属性和 Cext 的属性。 A 和 B 是 DTO,所以我想 有时将 B 作为 A 的“丰富”版本返回,而不更改名称、类型等。
最佳答案
泛型来救援。
class A<T extends C> {
protected String a;
protected String b;
.....
protected List<T> myList;
}
现在 myList
具有 T
类型的元素,它扩展了 C
。
当您使用 Aext
子类化 A
时,您可以指定 Cext
作为 myList
元素的类型。
class Aext extends A<Cext> {
String x;
}
关于DTO 中的 Java 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46623440/