2015-10-08 45 views
0

我被告知使用setter來更改對象的屬性,並讓setter驗證屬性被設置爲的數據。由於子類覆蓋,我還被告知不要在構造函數中使用setter。你應該如何驗證構造函數的參數,同時允許你的setters被覆蓋?你應該重複驗證碼嗎?構造函數參數驗證和設置器

隨着setter方法:

public class A { 
    private int x; 
    public A(int x){ 
     setX(x); 
    } 
    public void setX(int x) { 
     if (x > 6) 
      this.x = x; 
     else 
      this.x = 7; 
    } 
} 

沒有制定者:

public class A { 
    private int x; 
    public A(int x){ 
     this.x = x; 
    } 
    public void setX(int x) { 
     if (x > 6) 
      this.x = x; 
     else 
      this.x = 7; 
    } 
} 

沒有制定者和一倍代碼:

public class A { 
    private int x; 
    public A(int x){ 
     if (x > 6) 
      this.x = x; 
     else 
      this.x = 7; 
    } 
    public void setX(int x) { 
     if (x > 6) 
      this.x = x; 
     else 
      this.x = 7; 
    } 
} 
+0

你能發表一些代碼來證明你的問題是什麼嗎? –

回答

0

一個選項是你寫的是在使用的私有方法setter和構造函數中,所以你沒有加倍代碼,子類可以覆蓋setter容易。這是我的做法。

如果你不允許這樣做,你必須使用加倍的代碼。

----編輯:----

這僅是適合長時間的檢查,或者如果沒有缺省值應設置。

public class A { 
    private int x; 
    public A(int x){ 
    if(checkX()) 
     this.x=x; 
    else 
     this.x = 7; 
    } 
    public void setX(int x) { 
    if (checkX(x)) 
     this.x = x; 
    else 
     this.x = 7; 
    } 
    private boolean checkX(int x) { 
    if (x > 6) 
     return true; 
    else 
     retrun false; 
    } 
} 
+0

你能舉個例子嗎? –