2017-06-21 36 views
-3

在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等等。

所以,有2種方式,我通常看到的人做到這一點: -

1. B bObject = new B(aObject.geta(), aObject.getb(), aObject.getc(), aObject.getd()); 

其中一個構造函數在B中定義的所有參數從A

當值給出使用setter。

哪種方法更好?或者在某種情況下,每種方法都更有意義。

+0

大多數情況下,我會去與'構造函數'。如果不需要,我總是更喜歡沒有setter,只有一個構造函數具有所有可能的字段以避免「半支持對象」 – Mritunjay

回答

1

在這種情況下,我認爲構造方法更好。使用構造函數,你有機會使你的B對象不可變。如果你和setter一起去,你將無法做到這一點。

如果AB非常密切的關係,儘量使B的構造函數接受A

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

而且,這是非常罕見的與對應於另一個屬性在另一每個屬性創建這些類類。如果AB都是你寫的,你確定你沒有做錯什麼?考慮刪除其中的一個。如果其中一個不是由你寫的,你爲什麼要創建一個完全複製另一個類的屬性的類?你有沒有考慮使用包裝?

+0

這是我們在數據對象(從數據庫中取一個)和響應對象(由API)。那麼,對於這種情況,通常應該使用什麼?我不認爲在這種情況下,響應對象需要是不可變的。 – hatellla

+1

@hatellla在這種情況下,使用'A'作爲參數的構造函數。我還建議你在'A'和'B'中添加諸如'ToResponseObject'和'ToDataObject'等方法。然後你用這些方法調用構造函數。這種方式我認爲更具可讀性。關於可變性,不可變對象通常是一個好習慣。儘可能做到這一點。 – Sweeper

+0

非常感謝您的建議和良好的推理。 – hatellla

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); 
-3

乙bObject =新B(aObject.geta(),aObject.getb(),aObject.getc(),aObject.getd()); ,這是最好的做法,以創建其他對象。

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"); 
相關問題