Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does Java distinguish these multiple methods with the same name/signature?
    primarykey
    data
    text
    <p>I was tracking down a bug today, and I noticed something strange within one of our classes. I cut out as much code as possible to post here:</p> <pre><code>class A { static int obtainNumber() { return 42; } static int obtainNumber() { return 3; } static int obtainNumber() { return -1; } static { System.out.println(obtainNumber()); } } </code></pre> <p>This class has 3 methods with the exact same name and signature. At first I thought this was invalid code, but then eclipse would have highlighted the code in red. It does work:</p> <pre><code>javac A.java &amp;&amp; java A 42 Exception in thread "main" java.lang.NoSuchMethodError: main </code></pre> <p>So I figured maybe Java will just use the first one it sees. I reordered to test:</p> <pre><code>class A { static int obtainNumber() { return 3; } static int obtainNumber() { return -1; } static int obtainNumber() { return 42; } static { System.out.println(obtainNumber()); } } </code></pre> <p>Nope, same result:</p> <pre><code>javac A.java &amp;&amp; java A 42 Exception in thread "main" java.lang.NoSuchMethodError: main </code></pre> <p>I thought perhaps it uses the one with 42 because its the biggest. To test this, I took the original and changed the return values:</p> <pre><code>class A { static int obtainNumber() { return 0; } static int obtainNumber() { return 1; } static int obtainNumber() { return 2; } static { System.out.println(obtainNumber()); } } </code></pre> <p>It still knows to use the first one:</p> <pre><code>javac A.java &amp;&amp; java A 0 Exception in thread "main" java.lang.NoSuchMethodError: main </code></pre> <p>And if I reorder them again:</p> <pre><code>class A { static int obtainNumber() { return 1; } static int obtainNumber() { return 0; } static int obtainNumber() { return 2; } static { System.out.println(obtainNumber()); } } </code></pre> <p>Same result:</p> <pre><code>javac A.java &amp;&amp; java A 0 Exception in thread "main" java.lang.NoSuchMethodError: main </code></pre> <p>I thought Java was a text based language, which I'd expect makes this sort of thing impossible. How is Java tracking which method is which?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload