Home  >  Article  >  Java  >  What is method overloading in java?

What is method overloading in java?

青灯夜游
青灯夜游Original
2019-11-16 17:52:226070browse

What is method overloading in java?

What is method overloading in java?

Method overloading means that there can be multiple methods with the same name in a class, but the parameters of these methods must be different. Advantages: You only need to remember a single method name to achieve multiple similar functions.

What needs to be noted here is that different parameters need to meet two conditions. One is that the number of parameters is different, and the other is that the number of parameters is the same, but the type of a corresponding parameter in the parameter list is different.

The overloading of methods is related to the following factors:

1. Different number of parameters

2. Different parameter types

3. Multiple types of parameters The order is different

The overloading of the method has nothing to do with the following factors:

1. It has nothing to do with the name of the parameter

2. It has nothing to do with the return value type of the method

Example:

Question requirement: Compare two data to see if they are equal.

The parameter types are two byte types, two short types, two int types, and two long types.

And test it in the main method

public class CaiNiao{
    
    public static void main(String[] args){
        byte a = 10;
        byte b = 20;
        System.out.println(isSame(a,b));
        
        System.out.println((isSame(short)20,(short)20));
        
        System.out.println(isSame(11,22));
        
        System.out.println(isSame(10L,10L));
    }
    
    public static boolean isSame(byte a,byte b){
        System.out.println("两byte参数的方法执行!");
        boolean same ;
        if(a==b){
            same = true;
        }else{
            same = false;
        }
        return same;
    }

    public static boolean isSame(short a,short b){
        System.out.println("两short参数的方法执行!");
        boolean same = a == b ?true:false;
        return same;
    }
    
    public static boolean isSame(int a,int b){
        System.out.println("两int参数的方法执行!");
        return a == b:;
    }
    
    public static boolean isSame(long a,long b){
        System.out.println("两long参数的方法执行!");
        if (a==b){
            return true;
        }
        else{
            return false;
        }
    }
}

The above is the detailed content of What is method overloading in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What can java do?Next article:What can java do?