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
    }
}

分类:

技术点:

相关文章:

  • 2021-10-25
  • 2022-12-23
  • 2022-02-14
  • 2022-12-23
  • 2021-08-13
  • 2021-12-06
  • 2021-12-27
  • 2022-01-30
猜你喜欢
  • 2021-11-29
  • 2021-11-29
  • 2021-08-08
  • 2021-07-25
  • 2021-07-15
  • 2021-07-09
相关资源
相似解决方案