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

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

在java中向類變量添加值的優雅方法

在java中向類變量添加值的優雅方法

慕姐8265434 2022-08-03 12:45:58
我有一個班級說Studentpublic class Student {    private String name;    private int score;}假設我都有 getter/setter。目前,我有一個學生班級的對象說,它的分數值為50。我想在此對象中的分數中添加10。std我可以通過下面的代碼做到這一點:std.setScore(std.getScore() + 10);我正在尋找一種優雅的方法來寫出相同的方式,其中我不同時使用getter和setter,只需將分數增加10甚至1。使用++或類似+=10之類的東西說。
查看完整描述

2 回答

?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

編寫一個方法:


public void incrementScore(int amount) {

  score += amount;

}

是否允許負增量?如果沒有,請檢查它:


/**

 * Increments the score by the given amount.

 *

 * @param amount the amount to increment the score by; must not be negative

 * @throws IllegalArgumentException if the amount is negative

 */

public void incrementScore(int amount) {

  if (amount < 0) {

    throw new IllegalArgumentException("The increment must not be negative.");

  }

  score += amount;

}

這種方法比使用 /更優雅,因為:getset

  • 它允許您檢查參數,再考慮業務規則,

  • 它添加了一個業務方法,其名稱可以揭示意圖。

  • 它允許您編寫描述操作確切行為的JavaDoc注釋


查看完整回答
反對 回復 2022-08-03
?
浮云間

TA貢獻1829條經驗 獲得超4個贊

正如評論中所說,您可以在學生班級上創建新方法。


public class Student {

   private String name;

   private int score;


   public void incrementScore(int increment){

       this.score = this.score + increment;

   }

}

然后在 std 實例上調用它:


std.incrementScore(10)


查看完整回答
反對 回復 2022-08-03
  • 2 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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