Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: Methods that have same names?

in the Main method, I called foo(1), and it prints "foo a". So I don't understand why the compiler doesn't give me an error since these two methods have the same names.

I also tried to set them both private and public, and still works the same..

And then when I put that "foo b" method above the "foo a", then it prints "foo b". So does the compiler search for the method in order?

Here's all the code,

public class Practice{

  public static void main(String[] args) {
     foo(1);
  }


  private static void foo(int n){
    System.out.println("foo a");
  }

  public static void foo(int n){
    System.out.println("foo b");
  }

}
like image 741
Lazy Frog Avatar asked Apr 13 '26 23:04

Lazy Frog


2 Answers

Hmm. I can't get this to compile.

I think it could be a similar issue to How does Java distinguish these multiple methods with the same name/signature?.

Did you copy paste a method from somewhere, or did you type them in?

Perhaps this is also a holdover from a previous compilation effort. Did you try cleaning your project (/ deleting the executable), and then recompiling/running ?

Note: The code does not NORMALLY compile. You need to ignore errors on eclipse to get it to compile.

Hmm it really works! I think now that it must be an eclipse quirk, since I still can't get it to compile using javac. When you force compilation using eclipse, it must take the first one as valid. The second one throws a compiler error, which is subsequently ignored by eclipse. Therefore, you always print the result of the first method in the chain.

eclipse

Following the advice of Narendra Pathai and running javap on the compiled .class file does indeed show only one foo method :) [Yes, I added -private flag].

(result): Compiled from "Practice.java"

public class Practice extends java.lang.Object{
    public Practice();
    public static void main(java.lang.String[]);
    public static void foo(int);
}

(if you swap public-private): Compiled from "Practice.java"

public class Practice extends java.lang.Object{
    public Practice();
    public static void main(java.lang.String[]);
    private static void foo(int);
}
like image 131
Alexander Lin Avatar answered Apr 16 '26 13:04

Alexander Lin


Compile time error - Duplicate methods

It is not possible to have duplicate methods. Even eclipse gives error.

enter image description here

On answer to why can it still run:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

    at Main.main(Main.java:4)
like image 44
Narendra Pathai Avatar answered Apr 16 '26 12:04

Narendra Pathai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!