[英]Method overloading is not working as expected
In Java function overloading is on the type or number of a function parameter is I'm not correct please correct me 在Java函数重载是函数参数的类型或数量是我不正确请纠正我
I was going some test I found something not correct with Java overloading like public static void doSomeThing()
and public static int doSomeThing()
. 我正在进行一些测试,我发现一些不正确的Java重载,如
public static void doSomeThing()
和public static int doSomeThing()
。
Both the function is the same and it should not compile but it's running. 这两个函数都是相同的,它不应该编译但它正在运行。
Like this code. 喜欢这段代码。
package com.sudeep.test;
public class StaticFunctionOverload {
public static void main(String arg[]) {
doSomeThing();
}
public static int doSomeThing() {
System.out.println("Im in int block");
return -1;
}
public static void doSomeThing() {
System.out.println("Im in void block");
}
}
Methods' signatures must be different: 方法的签名必须不同:
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures.
Java编程语言支持重载方法,Java可以区分具有不同方法签名的方法。 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").
这意味着如果类中的方法具有不同的参数列表,则它们可以具有相同的名称(有一些资格,将在标题为“接口和继承”的课程中讨论)。
Read this: 读这个:
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
So, this will work, for example: 所以,这将起作用,例如:
package com.sudeep.test;
public class StaticFunctionOverload {
public static void main(String arg[]) {
doSomeThing();
}
public static int doSomeThing() {
System.out.println("Im in int block");
return -1;
}
public static void doSomeThing(int param1) {
System.out.println("Im in void block with " + param1);
}
}
As has been mentioned multiple times, it should not compile. 正如已经多次提到的那样,它不应该编译。 But I also see your screenshot and the confusion when it actually runs on your computer.
但是我也看到了你的截图以及它在你的计算机上实际运行时的混乱。
I think what you are seeing there is a "feature" of eclipse where it would run an older build of the class when it encounters errors . 我认为你所看到的是eclipse的一个“特性”, 当它遇到错误时会运行一个较旧的类 。 I presume you have previously built and run the class with only the
int
method, before you added the void
one. 我假设您在添加
void
之前已经使用int
方法构建并运行该类。
If that is the case, there are a couple things you can do: 如果是这种情况,您可以做以下几件事:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.