【问题标题】:Multiple getter methods for different amount of parameters用于不同数量参数的多个 getter 方法
【发布时间】:2016-02-27 21:13:21
【问题描述】:

我知道你可以有多个构造函数,例如:

public Game (int num, boolean truth) {

}

public Game (int num) {
    this(num, false);
}

getter 方法也可以这样做吗?所以我可以有两个参数,但是如果用户只想使用一个,另一个会自动填写。比如

public int wins (int num, boolean truth) {
    return num*2;
}

public int wins (int num) {
    this(num, false);
}

【问题讨论】:

    标签: java object methods constructor getter


    【解决方案1】:

    是的,您可以这样做,这称为overloading

    public class DataArtist {
        ...
        public void draw(String s) {
            ...
        }
        public void draw(int i) {
            ...
        }
        public void draw(double f) {
            ...
        }
        public void draw(int i, double f) {
            ...
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以声明一个委托方法,例如:

      public int wins (int num, boolean truth) {
          return num * 2;
      }
      
      public int wins (int num) {
          return wins(num, false);
      }
      

      在这种情况下,this 关键字仅用于调用构造函数。

      【讨论】:

        猜你喜欢
        • 2018-05-21
        • 2019-03-10
        • 2017-09-06
        • 2017-09-30
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-24
        相关资源
        最近更新 更多