哪个是从另一个对象创建一个对象的更好实践

时间:2017-06-21 05:29:54

标签: java

在Java中,比方说,我有两个类: -

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())

使用setter给出值。

哪种方法更好?或者在某些情况下,每种方式都更有意义。

4 个答案:

答案 0 :(得分:1)

您可以将A作为B的构造函数中的参数。

class B {
    int x;
    int y;
    String e;
    String f;

    B(A aObject) {
        x = aObject.geta();
        y = aObject.getb();
        e = aObject.getc();
        f = aObject.getd();
    }
}

然后,

B bObject = new B(aObject);

答案 1 :(得分:1)

在这种情况下,我认为构造函数方法更好。使用构造函数,您有机会使B个对象不可变。如果你选择了setter,你将无法做到这一点。

如果AB 非常密切相关,请尝试让B的构造函数接受A

public B(A a) {
    x = a.getA();
    y = a.getB();
    e = a.getC();
    f = a.getD();
}

此外,使用与另一个类中的另一个属性对应的每个属性创建这些类非常罕见。如果AB都由您撰写,您确定自己没有做错吗?考虑删除其中一个。如果其中一个不是您编写的,为什么要创建一个完全复制另一个类的类?属性?您是否考虑过使用包装器?

答案 2 :(得分:0)

您可以通过Constructor链接:

执行此操作

您应该使用inheritancesuper关键字将您的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");

答案 3 :(得分:-3)

B bObject = new B(aObject.geta(),aObject.getb(),aObject.getc(),aObject.getd()); ,这个将是从其他人创建对象的最佳实践。