Java重载如何工作?

时间:2020-10-28 15:00:27

标签: java overloading

假设我有这个Java程序。为什么打印“ foo”?

class Foo {}

class Bar extends Foo {}

class Main {
    
    public static void main(String[] argv) {
        Foo object = new Bar();
        
        printSomething(object);
    }

    public static void printSomething(Foo f) {
        System.out.println("foo");
    }

    public static void printSomething(Bar b) {
        System.out.println("bar");
    }
}

我知道重写和后期绑定,但是我不习惯重载吗?是否在运行时检查 object 的类型,以便调用最特定的方法?那原始值呢?

1 个答案:

答案 0 :(得分:1)

重载基本上是使用具有不同参数的相同方法名称。您的示例将打印“ foo”,因为您正在向其传递类型为Foo的对象,而Java调用了第一个重载,因为它期望这样的对象。让我们做一个更简单的示例(自您询问以来,使用基元):

class Main {
    
    public static void main(String[] argv) {
        addPrint(15, 20);
        addPrint("Hello, ", "world!");
    }

    // This method will add two ints and print the result.
    public static void addPrint(int a, int b) {
        System.out.println(a + b);
    }

    // This is the same as the first method, but it will add Strings instead.
    // Please note - do not use a method for this. This is done purely for the example.
    public static void addPrint(String a, String b) {
        System.out.println(a + b); // this will add the two strings together just like ints
    }
}

这实际上是首先使用参数addPrint(int, int)15调用20,它们是整数,因此Java将知道要调用的内容,因为第一个重载需要两个整数。第二次,它将查找带有两个String(或从String继承的类)的重载,如果找到了某些东西,它将对其进行调用。否则,它将在编译期间哭泣,找不到合适的重载。

您也可以参考this article了解更多信息。

提示-重载在其他语言中的作用几乎相同,例如C#。

相关问题