Java方法的重载

Java方法的重载

方法重载:在类中方法名称相同,但是形式参数不同

public class Demo15 {
   public static void main(String[] args) {
     int sum=  max(30,30);
       System.out.println(sum);
       double sumDouble = max(33.2,55.4);

  }
   public static int max(int a,int b){
       int result = 0;
       if (a==b){
           System.out.println("a==b");
           return 0;

      }
       if (a>b){
           result = a;
      }else {
           result = b;
      }
       return result;

  }//方法的名称相同都是max
   public static int max(int c,int d){
       int result = 0;
       if (a==b){
           System.out.println("a==b");
           return 0;

      }
       if (a>b){
           result = a;
      }else {
           result = b;
      }
       return result;

  }//这样的写法是错误的因为方法名相同而且形式参数也相同
   // 系统无法识别
   public static double max(double a,double b){

       if(a==b){
           System.out.println("a==b");
           return 0;
      }
       if (a>b){
           return a;
      }else {
           return b;

      }

  }//但是方法的类型不同double和int
    public static double max(double a,double b,double c){

       if (a==b && b==c){
           System.out.println("a==b==c");
           return 0;

      }
       if (a>b && a>c){
           return a;
      }else if(b>a && b>c){
           return b;
      }else if (c>a && c>b){
           return c;
      } return 0;
      }
       //形式参数个数不同也可以
   public static int max(int a,int b,int c){//方法名字相同个数不同但是实现的功能却全然不同
                                           //这也是重载
       return a+b+c;
  }
}

总结重载的实现条件:

  • 在类中方法名字必须相同

  • 形式参数必须不同(类型不同,个数不同)

  • 重载后实现的功能也可以不同

  •  

posted @ 2021-03-07 08:54  默默努力的路人甲  阅读(98)  评论(0)    收藏  举报