Overload with different return type in Java?

2019-01-02 17:37发布

Why is it not possible to overload a function just by changing the return type? Will that change in a future version of Java?

By the way, just for reference, is this possible in C++?

8条回答
永恒的永恒
2楼-- · 2019-01-02 18:15

The reason is that overloads in Java are only allowed for methods with different signatures.

The return type is not part of the method signature, hence cannot be used to distinguish overloads.

See Defining Methods from the Java tutorials.

查看更多
高级女魔头
3楼-- · 2019-01-02 18:16

Return type does not matter while overloading a method. We just need to ensure there is no ambiguity!

The only way Java can know which method to call is by differentiating the types of the argument list. If the compiler allowed two methods with the same name and same argument types, there would be no way to determine which one it should call.

查看更多
与风俱净
4楼-- · 2019-01-02 18:19

Overloaded methods in java may have different return types given that the argument is also different.

Check out the sample code.

public class B {

    public String greet() {
        return "Hello";
    }

    //This will work
    public StringBuilder greet(String name) {
        return new StringBuilder("Hello " + name);
    }

    //This will not work
    //Error: Duplicate method greet() in type B
    public StringBuilder greet() {
        return new StringBuilder("Hello Tarzan");
    }

}
查看更多
不流泪的眼
5楼-- · 2019-01-02 18:26

Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

查看更多
倾城一夜雪
6楼-- · 2019-01-02 18:27

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

查看更多
梦该遗忘
7楼-- · 2019-01-02 18:33

no not really possible that way you can only overload by no of arguments or data type of the arguments

查看更多
登录 后发表回答