[Java method learning] method overload

Method overloading

Overloading is a function with the same function name but different formal parameters in a class.

下面三个方法名字都相同为max(),但是参数类型不同
//比大小,两个整数
public static double max(double num1,double num2) {
    
    
    //修饰符 修饰符 返回值类型 名字
    double result = 0;
    if (num1 == num2) {
    
    
        System.out.println("num1=num2");
        return 0;
    }
    if(num1>num2){
    
    
        result = num1;
    }else {
    
    
        result =num2;
    }
    return result;
}
//比大小,两个浮点数
public static int max(int num1,int num2){
    
    
    //修饰符 修饰符 返回值类型 名字
    int result=0;
    if(num1==num2){
    
    
        System.out.println("num1=num2");
        return 0;
        /*return还可以用来结束方法,如果相等会输出两行:
        num1=num2
        0
         */
    }
    if(num1>num2){
    
    
         result = num1;
    }else {
    
    
         result =num2;
    }

    return result;//return一般写在方法最下面
}
//比大小,三个数
public static int max(int num1,int num2,int num3){
    
    
    //修饰符 修饰符 返回值类型 名字
    int result=0;
    if(num1==num2){
    
    
        System.out.println("num1=num2");
        return 0;
        /*return还可以用来结束方法,如果相等会输出两行:
        num1=num2
        0
         */
    }
    if(num1>num2){
    
    
        result = num1;
    }else {
    
    
        result =num2;
    }

    return result;//return一般写在方法最下面
}

The rules of method overloading:

1**. The method name must be the same**. As above

2**. The parameter list must be different** (the number is different, or the type is different, the order of the parameters is different, etc.). As above

3. The return type of the method can be the same or different. As above

4. Different return types alone are not enough to be overloads of methods. As above

Realization theory:

When the method name is the same, the compiler will match one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error

Guess you like

Origin blog.csdn.net/weixin_44302662/article/details/114648704