Java方法的重载

时间:2021-03-08 13:32:56   收藏:0   阅读:0

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

总结重载的实现条件:

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!