在Java中,比如说,我有2个类:-
class A {
int a;
int b;
String c;
String d;
}
class B {
int x;
int y;
String e;
String f;
}
现在,假设我有一个类 A 的对象,即 aObject,我想创建一个类 B 的对象,其中 x 对应于 a,y 对应于 b,依此类推。
所以,我通常有两种方法可以让人们这样做:-
1. B bObject = new B(aObject.geta(), aObject.getb(), aObject.getc(), aObject.getd());
其中,构造函数在 B 中为 A 中的所有参数定义。
2. B bObject = new B();
bObject.setx(aObject.geta())
bObject.sety(aObject.getb())
bObject.sete(aObject.getc())
bObject.setf(aObject.getd())
其中使用二传手给出值。
哪种方法更好?或者在某些情况下,每种方式都更有意义。
在这种情况下,我认为构造函数方法更好。使用构造函数,您有机会使B
对象不可变。如果你选择二传手,你将无法做到这一点。
如果A
和B
非常密切相关,请尝试使B
的构造函数接受A
:
public B(A a) {
x = a.getA();
y = a.getB();
e = a.getC();
f = a.getD();
}
此外,创建这些类的情况非常罕见,每个属性都对应于另一个类中的另一个属性。如果A
和B
都是你写的,你确定你没有做错什么吗?请考虑删除两者之一。如果其中一个不是由您编写的,为什么要创建一个完全复制另一个类属性的类?您是否考虑过使用包装器?
Constructor
链接来执行此操作:
您应该使用 inheritance
和 super
关键字将类 B 变量引用为 A 类参数,如以下代码所示:
class A {
int a;
int b;
String c;
String d;
public A(int a, int b, String c, String d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
class B extends A{
int x;
int y;
String e;
String f;
public B(int x, int y, String e, String f) {
super(x,y,e,f);
//Above line call super class Constructor , Class A constructor .
this.x = x;
this.y = y;
this.e = e;
this.f = f;
}
}
A ARefrenceobjB = new B(1,2,"str1","str2");
(, aObject.getc((, aObject.getd(((; ,这将是从其他对象创建对象的最佳实践。