Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is not improper to say that "static nested classes" are not nested classes at all. It is convenient to discuss static nested classes in the context of inner classes because the way they are declared in code is similar and also because a static nested class still has to be named with the enclosing class as a context.</p> <p>However, here is an important thing to keep in mind about static nested classes: from the point of view of the compiler and the JVM, static nested classes are top level classes. In fact, the compiler implements them logically at compile time as top level classes (at least it used to; I think it still does).</p> <p>Why, then, should anyone ever use static nested classes? Why not just write top level classes all the time?</p> <p>For me, static nested classes provide a convenient mechanism for logically grouping closely related classes in a manner that keeps my project hierarchy nice and tidy. For example, say that I have a database with the following tables: Clients, Encounters, and Services. I -could- model these tables with separate top-level classes and it would work fine, but since these tables are all in the same database and relate to the same data, I find it convenient to model these as:</p> <pre><code>class DB { static class Client { ... } static class Encounter { ... } static class Service { ... } } </code></pre> <p>To use an instance of one of the models:</p> <pre><code>DB.Encounter enc = new DB.Encounter(); </code></pre> <p>In my view, this makes code more readable since it is immediately clear in the code that the object that is being created derives from one of my database models. It also keeps the class definitions for the models linked under a common heading which I also think helps make projects simpler to understand.</p> <p>But from the point of view of the JVM (and the compiler, which implements them as top level classes anyway [just as it also gives "anonymous" inner classes names at compile time]), these objects are instantiated from top level classes. Making them does not depend on any instance of any object, nor can objects instantiated from a static nested class access any private members of the enclosing class.</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