重载或普通方法

Overloading or a normal method

我提出这个问题是为了对 java 中的 Concept 重载有一个清晰的认识。根据我的理解,重载编译器中的方法解析将查找方法签名,即它应该具有相同的方法名称和不同的参数类型。但是,如果 return 类型不同怎么办??

class Test{
    public void m1(int i) {
    System.out.println(" int arg");
}

public int m1(String s) {
    System.out.println("String-arg");
    return (5+10);
}

public static void main (String[] args) throws java.lang.Exception
{
    Test t = new Test();
    t.m1(5);
    int i = t.m1("ani");
    System.out.println(i);
}}

以上程序 运行 非常完美。我的疑问是,方法 m1() 是否重载了??它有不同的 return 类型。有人请说清楚。提前致谢

Java 中,方法由名称和参数“类”和数量标识。 return 类型不识别方法。因此,以下代码是非法的:

public void m1(String i) {

    System.out.println(" int arg");
}

public int m1(String s) {

    System.out.println("String-arg");
    return (5+10);
}

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded. (...) When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4)

总而言之,两个同名的方法可以 return 不同的类型,但是在决定调用哪个方法时不会考虑这一点。 JVM 首先决定调用哪个方法,然后检查该方法的 return 类型是否可以分配给特定变量。

例子(尽量避免这样的结构):

public int pingPong(int i) {
    return i;
}
public String pingPong(String s) {
    return s;
}
public boolean pingPong(boolean b) {
    return b;
}

如果我们按照Oracle定义那么,它是一个重载方法

这里 info(强调我的)

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").

方法 return 值与否与重载定义无关的事实...

另一件事是为什么一个方法有时 return 一个值有时没有...

这会让使用代码的人发疯,但这是另一个问题...