Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing an inner class name and an object name same in Java
    primarykey
    data
    text
    <p>In the following code snippet, presumably it appears that it should issue some compilation error but it doesn't:</p> <pre><code>class Outer { public static class Inner { static String obj = "Inner"; } static Optional Inner = new Optional(); //The (inner) class name and the object name are same. } class Optional { String obj = "Optional"; } public class Main { public static void main(String[] args) { System.out.println(Outer.Inner.obj); //Refers to the string inside the optional class } } </code></pre> <p>The class <code>Outer</code> has a static class inside it named <code>Inner</code>. Additionally, it declares an object (static) of the class <code>Optional</code> (<code>static Optional Inner = new Optional();</code>)</p> <p>This object and the class names (inside the class <code>Outer</code>) are same which is <code>Inner</code>. The program displays <code>Optional</code>. The only expression <code>Outer.Inner.obj</code> within <code>main()</code> is expected to display <code>Inner</code> but it doesn't. The actual output is however <code>Optional</code> which is the case of the <code>Optional</code> class. </p> <p>One way to display <code>Inner</code> is by changing the object name to something else.</p> <pre><code>static Optional Inner1 = new Optional(); </code></pre> <p>From the output it displays, it appears that the object name (or a variable) is chosen over a type name (the class <code>Inner</code>) because they have the same name. What exact case is applied here?</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.
 

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