1 回答

TA貢獻1789條經驗 獲得超8個贊
首先,您的 chargeMax 似乎是一個常量值,不需要在構造函數中接收其值(10000)。您可以直接在其字段聲明中執行此操作。
其次,您可以在構造函數中添加一些邏輯。該邏輯取決于您的需要。當構造函數接收到大于 chargeMax 的值時,您可以自動使 charge 接收 chargeMax。
例如:
public class Vehicle {
protected String immat;
protected int poidsVide;
protected int charge;
protected static final int CHARGE_MAX = 10000; // this is a constant
Vehicle(String immat, int poidsVide, int charge) {
this.immat = immat;
this.poidsVide = poidsVide;
if (charge > CHARGE_MAX){
this.charge = CHARGE_MAX;
}
else {
this.charge = charge;
}
}
}
另一個想法是當 Vehicle 收到一些不需要的值時拋出異常:
Vehicle(String immat, int poidsVide, int charge) {
this.immat = immat;
this.poidsVide = poidsVide;
if (charge > CHARGE_MAX){
throw new IllegalArgumentException("Charge cannot be bigger than " + CHARGE_MAX);
}
else {
this.charge = charge;
}
}
添加回答
舉報