Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Java always chooses the most <em>specific</em> method (or constructor) that would be applicable for the argument you pass. In this case, that's the <code>String</code> constructor -- <code>String</code> is a subclass of <code>Object</code>.</p> <p>Think about what would happen if you had </p> <pre><code>new Test("some string") </code></pre> <p><em>Both</em> the <code>Object</code> and <code>String</code> constructors would be applicable here. After all, the argument is both an <code>Object</code> and a <code>String</code>. <em>However</em>, it is clear that the <code>String</code> constructor will be invoked because it is more specific than the <code>Object</code> constructor and still is applicable given the argument.</p> <p><code>null</code> is no different; these two constructors are still applicable, and the <code>String</code> constructor is still chosen over the <code>Object</code> one for the same reason.</p> <p>Now, if there were two equally "specific" constructors present (e.g. if you had an <code>Integer</code> constructor) there would be a compilation error when you call <code>Test(null)</code>.</p> <p>This is outlined in more detail in <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2" rel="noreferrer">JLS §15.12.2</a>:</p> <blockquote> <p>The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.</p> <p>There may be more than one such method, in which case the <em>most specific</em> one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.</p> </blockquote> <p>The explicit process of determining which method is the most specific is outlined in <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5" rel="noreferrer">JLS §15.12.2.5</a>.</p>
 

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