Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p><em>what I want to know is why java forbids static fields/methods inside inner classes</em></p> </blockquote> <p>Because those inner classes are "instance" inner classes. That is, they are like an instance attribute of the enclosing object. </p> <p>Since they're "instance" classes, it doesn't make any sense to allow <code>static</code> features, for <code>static</code> is meant to work without an instance in the first place.</p> <p>It's like you try to create a static/instance attribute at the same time. </p> <p>Take the following example: </p> <pre><code>class Employee { public String name; } </code></pre> <p>If you create two instances of employee: </p> <pre><code>Employee a = new Employee(); a.name = "Oscar"; Employee b = new Employee(); b.name = "jcyang"; </code></pre> <p>It is clear why each one has its own value for the property <code>name</code>, right? </p> <p>The same happens with the inner class; each inner class instance is independent of the other inner class instance.</p> <p>So if you attempt to create a <code>counter</code> class attribute, there is no way to share that value across two different instances. </p> <pre><code>class Employee { public String name; class InnerData { static count; // ??? count of which ? a or b? } } </code></pre> <p>When you create the instance <code>a</code> and <code>b</code> in the example above, what would be a correct value for the static variable <code>count</code>? It is not possible to determine it, because the existence of the <code>InnerData</code> class depends completely on each of the enclosing objects. </p> <p>That's why, when the class is declared as <code>static</code>, it doesn't need anymore a living instance, to live itself. Now that there is no dependency, you may freely declare a static attribute.</p> <p>I think this sounds reiterative but if you think about the differences between instance vs. class attributes, it will make sense. </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