Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing outer class members from within an inner class extending the outer class itself
    text
    copied!<p>In the code snippet shown below, an inner class inherits an outer class itself.</p> <pre><code>package test; class TestInnerClass { private String value; public TestInnerClass(String value) { this.value = value; } private String getValue() { return value; } public void callShowValue() { new InnerClass("Another value").showValue(); } private final class InnerClass extends TestInnerClass { public InnerClass(String value) { super(value); } public void showValue() { System.out.println(getValue()); System.out.println(value); } } } </code></pre> <hr> <pre><code>public final class Test { public static void main(String[] args) { new TestInnerClass("Initial value").callShowValue(); } } </code></pre> <p>The only statement inside the <code>main()</code> method (the last snippet) assigns the value <code>Initial value</code> to the private field <code>value</code> of the <code>TestInnerClass</code> class and then invokes the <code>callShowValue()</code> method.</p> <p>The <code>callShowValue()</code> method causes another string - <code>Another value</code> to be set the to the private field <code>value</code> of the <code>TestInnerClass</code> class before invoking the <code>showValue()</code> method of <code>InnerClass</code> extending <code>TestInnerClass</code>.</p> <p>Accordingly, the following two statements inside the <code>showValue()</code> method,</p> <pre><code>System.out.println(getValue()); System.out.println(value); </code></pre> <p>should display,</p> <blockquote> <p>Another value<br> Another value</p> </blockquote> <p>But they display,</p> <blockquote> <p>Initial value<br> Initial value</p> </blockquote> <p>Why does this happen?</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