[英]How to implement constructor for extended class
This works: 这有效:
class ABean implements A {
protected String field1;
...
protected String fieldn;
public String getField1() {
return field1;
}
...
}
class BBean extends ABean {
public BBean(A a) {
super();
this.field1=a.getField1();
...
this.fieldn=a.getFieldn();
}
}
But writing this constructor B(A a)
is cumbersome, not really practical, and error prone because if I add or remove fields in A
, then I need to modify that constructor and may sometimes forget to initialize some of the fields present in A
. 但是编写此构造函数B(A a)
很麻烦,不实际,并且容易出错,因为如果我在A
添加或删除字段,那么我需要修改该构造函数,有时可能会忘记初始化A
存在的某些字段。
I suppose I could implement clone for ABean, but that would have similar issues (because the clone implementation would need to be updated when I add/remove fields) and that would also not allow me to have a BBean(A a)
constructor; 我想我可以为ABean实现克隆,但是会有类似的问题(因为在添加/删除字段时需要更新克隆的实现),并且也不允许我拥有BBean(A a)
构造函数; only a BBean(ABean a)
constructor unless I make the clone()
part of the interface also. 除非我也将clone()
BBean(ABean a)
接口的一部分,否则只能是BBean(ABean a)
构造函数。
So... is there a cleaner, better way of implementing BBean(A a)
? 那么... 有没有更清洁,更好的方法来实现BBean(A a)
?
Instead of using inheritance, try using composition. 而不是使用继承,请尝试使用组合。 That is, instead of BBean extends ABean
, make your BBean
have a constructor BBean(ABean a)
. 也就是说,不是让BBean extends ABean
,而是让您的BBean
具有构造函数BBean(ABean a)
。 That way you've shielded yourself from all the details of how to construct a new ABean
in BBean
's code. 这样,您就避免了如何在BBean
的代码中构造新的ABean
所有细节。
What about implementing an "A"-constructor (copy-constructor) on your ABean as follows: 如何在ABean上实现“ A”构造函数(复制构造函数),如下所示:
class ABean implements A {
protected String field1;
...
protected String fieldn;
public String getField1() {
return field1;
}
...
public ABean(A other) {
this.field1=other.getField1();
...
this.fieldn=other.getFieldn();
}
}
class BBean extends ABean {
public BBean(A a) {
super(a);
}
}
This way, your "copy-constructor" mapping for A's is all in your ABean. 这样,您的A的“复制构造函数”映射就位于您的ABean中。
you can use reflection: 您可以使用反射:
class A {}
class B {
public B(A a) {
String methodName = null;
try {
Field[] fields = a.getClass().getDeclaredFields();
for (Field field : fields) {
methodName = field.getName().substring(0, 1).toUpperCase()
+ field.getName()
.substring(1, field.getName().length());
field.get(a);
this.getClass().getMethod("set" + methodName, field.getClass()).invoke(a, field.get(a));
}
} catch (Exception e) {
e.printStackTrace();
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.