Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>My question is, why isn't ClassB's method being used?</p> </blockquote> <p>Not true. The method used is <code>ClassB</code>'s method, which it inherited from <code>ClassA</code>.</p> <hr> <p>I think the main reason behind the confusion here is the fact that the method actually is not <strong>overridden</strong>, instead it is <strong>overloaded</strong>. Although <code>Integer</code> is a subtype of <code>Number</code>, since <em>method parameter is invariant</em> in Java, the method <code>public void method(Integer d)</code> doesn't override the method <code>public void method(Number n)</code>. So, <code>ClassB</code> ends up having two (overloaded) methods.</p> <p>Static binding is used for overloaded methods, and the method with most specific parameter type is chosen by the compiler. But in this case, why does the compiler pick <code>public void method(Number n)</code> instead of <code>public void method(Integer d)</code>. That's because of the fact that the reference that you are using to invoke the method is of type <code>ClassA</code>. </p> <pre><code>ClassA a = new ClassB(); //instance is of ClassB (runtime info) a.method(3); //but the reference of type ClassA (compiletime info) </code></pre> <p>The only method that <code>ClassA</code> has is <code>public void method(Number n)</code>, so that's what the compiler picks up. Remember, here the expected argument type is <code>Number</code>, but the actual argument, the integer 3, passed is auto-boxed to the type <code>Integer</code>. And the reason that it works is because the <em>method argument is covariant</em> in Java. </p> <p>Now, I think it's clear why it prints</p> <blockquote> <p>ClassA: 3 class java.lang.Integer</p> </blockquote>
    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. 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