简体   繁体   中英

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

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");
    }

}

代码出错但仍在eclipse上运行

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:

  1. If you actually want to keep this feature (launch older version when errors exist), you can do a clean (menu: Project > Clean... ) to clear the previously built version. If you now attempt to run, Java will stop and complain that it can't build your source.
  2. If you think this "feature" may actually be detrimental, go to Window > Preferences > Run/Debug > Launching > Continue launch if project contains errors > Prompt

在此输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM