In Java function overloading is on the type or number of a function parameter is I'm not correct please correct me
I was going some test I found something not correct with Java overloading like public static void doSomeThing()
and 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. 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
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 . I presume you have previously built and run the class with only the int
method, before you added the void
one.
If that is the case, there are a couple things you can do:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.