亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

java 構造函數,其參數具有最大值

java 構造函數,其參數具有最大值

白板的微信 2023-09-06 17:14:22
從Java開始,我希望構造函數中的參數之一在創建時不超過某個值。舉個例子 :public class Vehicule {    protected String immat;    protected int poidsVide;    protected int charge;    protected int chargeMax;    Vehicule(String immat, int poidsVide, int charge) {        this.immat = immat;        this.poidsVide = poidsVide;        this.charge = charge;        this.chargeMax = 10000;   }}我不希望任何對象實例化為“charge”優于“chargeMAx”,我應該怎么做?嘗試了幾種選項,到目前為止沒有任何效果。感謝您的幫助。
查看完整描述

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;

    }

}


查看完整回答
反對 回復 2023-09-06
  • 1 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號