Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let us walk through the JVM:</p> <pre><code>B b1 = new B(){ int m(A a,A b) { return 10; } }; </code></pre> <p>This creates an instance of <code>B</code> with an anonymous overload of method <code>m()</code> having two arguments of type <code>A</code>. But this is a <em>different</em> <code>m()</code> method than what class <code>B</code> (or <code>A</code>) defines, since their <em>signature</em> (<code>A, A</code> vs <code>A, B</code>) differ.</p> <p>Then:</p> <pre><code>System.out.println(b1.m(b1, b1)); </code></pre> <p>This calls <code>b1</code>'s <code>m()</code> method with two arguments of type <code>B</code>.</p> <p>Now the JVM looks up what <code>m()</code> is:</p> <ul> <li>there is no method <code>m()</code> having two arguments of type <code>B</code>;</li> <li>in class <code>B</code>, it finds a match: a method by name <code>m()</code> whose first argument is a <code>A</code> (since <code>B</code> inherits <code>A</code>) and a second argument which is of type <code>B</code>;</li> <li><strong>the anonymous overloading by <code>b1</code> is <em>completely ignored</em> here!</strong> (see <a href="https://gist.github.com/fge/5762353" rel="nofollow">https://gist.github.com/fge/5762353</a>)</li> <li>end of method lookup.</li> </ul> <p>The <code>m()</code> method of class <code>B</code> is therefore invoked. And in this method, we have:</p> <pre><code>if (a1 == a2) // TRUE! return x; </code></pre> <p>Since the condition is true (the method has been called with the two arguments being the exact same object references), the value of <code>x</code> must be returned; and <code>x</code> is defined by class <code>A</code>, which class <code>B</code> <code>extends</code>:</p> <pre><code> public static int x = 1; </code></pre> <p>Since this is a <strong>static</strong> member of class A (which class B does not hide) it is equally accessible by instance methods, from any instance of <code>A</code> or <code>B</code>; therefore, the return code, and output of this program, is 1.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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