cloudsir

在 JAVA 语言中,并没有提供像 C++、Python 等语言提供的默认参数特性,必须通过函数重载实现。

普通函数的默认参数

public class Main {
    
    public static int sum(int a, int b){
        return a + b;
    }
    
    public static int sum(int a){
        return sum(a, 2);  // 当只有一个参数时,默认 b=2
    }
    
    public static void main(String[] args) {
        System.out.println(sum(1));      // 输出3
        System.out.println(sum(1, 3));   // 输出4
    }
}

构造函数的默认参数

public class main {

    public static class SUM{
        private int a, b;
        
        // 当只有一个参数时,默认 b=2
        public SUM(int a){
            // 重载当前类的构造函数必须利用this()构造器
            // 且this()必须在第一行
            this(a, 2);
        }
        
        public SUM(int a, int b){
            this.a = a;
            this.b = b;
        }

        @Override
        public String toString() {
            return a + b + "";
        }
    }
    public static void main(String[] args) {
        System.out.println(new SUM(1));      // 输出3
        System.out.println(new SUM(1, 3));   // 输出4
    }
}

分类:

技术点:

相关文章:

  • 2018-02-13
  • 2021-09-18
  • 2021-12-29
  • 2021-05-12
  • 2021-06-01
  • 2021-09-14
  • 2022-01-01
  • 2021-10-09
猜你喜欢
  • 2021-11-29
  • 2021-11-29
  • 2021-08-08
  • 2021-12-06
  • 2020-01-17
  • 2021-11-02
  • 2021-10-19
相关资源
相似解决方案