方法重载
方法重载 (也称为函数重载 )是类具有多个具有相同名称的方法的能力,允许它们在参数的数量或类型上有所不同。
编译器检查方法重载的方法签名。
方法签名包含三件事 -
- 方法名称
- 参数数量
- 参数类型
如果这三个对于类中的任何两个方法都相同,那么编译器会抛出重复的方法错误。
这种类型的多态称为静态或编译时多态,因为在编译期间编译器根据参数列表决定要调用的适当方法。
class Polymorph {
    public int add(int a, int b){
        return a + b;
    }
    
    public int add(int a, int b, int c){
        return a + b + c;
    }
    public float add(float a, float b){
        return a + b;
    }
    public static void main(String... args){
        Polymorph poly = new Polymorph();
        int a = 1, b = 2, c = 3;
        float d = 1.5, e = 2.5;
        System.out.println(poly.add(a, b));
        System.out.println(poly.add(a, b, c));
        System.out.println(poly.add(d, e));
    }
}
这将导致:
2
6
4.000000
重载方法可以是静态的或非静态的。这也不会影响方法重载。
public class Polymorph {
    private static void methodOverloaded()
    {
        //No argument, private static method
    }
 
    private int methodOverloaded(int i)
    {
        //One argument private non-static method
        return i;
    }
 
    static int methodOverloaded(double d)
    {
        //static Method
        return 0;
    }
 
    public void methodOverloaded(int i, double d)
    {
        //Public non-static Method
    }
}
此外,如果你更改方法的返回类型,我们无法将其作为方法重载。
public class Polymorph {  
void methodOverloaded(){
    //No argument and No return type
}
int methodOverloaded(){
    //No argument and int return type 
    return 0;
}