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;
}
}
你能發表一些代碼來證明你的問題是什麼嗎? –