[英]cast or create obj1 from obj2 where obj1 and obj2 extends same abstract class
For example I have: 例如,我有:
public abstract class SomeAbstract {
private int a;
private int b;
..
private int z;
}
public class A extends SomeAbstract {
private String aField;
}
public class B extends SomeAbstract {
private long bField;
}
(default constructors/setters/getters are omitted) (省略了构造函数/ setter / getters的默认值)
I have some instance of a class A and i wanna create instance of a class B from A(abstract fields). 我有一个A类的实例,我想从A(抽象字段)创建一个B类的实例。
Yes, I can use abstract class constructor or create constructor for class B like this : 是的,我可以使用抽象类构造函数或为类B创建构造函数,如下所示:
public B(A a) {
this.a = a.getA();
this.b = a.getB();
..
this.z = a.getZ();
}
But since I have many fields this does not look nice and convenient Is there another way? 但是因为我有很多字段,所以看起来不太方便又有另外一种方法吗?
You can create a constructor in the super class that receives another super class. 您可以在超类中创建一个接收另一个超类的构造函数。
public abstract class SomeAbstract {
/* attributes... */
public SomeAbstract() {
}
protected SomeAbstract(SomeAbstract another) {
this.a = another.a;
/* and on... */
}
}
And reuse this constructor in sub classes: 并在子类中重用此构造函数:
public class B extends SomeAbstract {
public B(A a) {
super(a);
this.specificAttribute = a.somethingElse;
}
}
If you have that many fields and don't want/need to create the whole code manually, you can use an external library that helps you with the mapping between classes. 如果您有许多字段并且不希望/需要手动创建整个代码,则可以使用外部库来帮助您进行类之间的映射。 Some options are:
一些选项是:
b.setValue(a.getValue()))
. b.setValue(a.getValue()))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.