<p>What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?</p>

[{'answer_id': 70339, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 3, 'selected': False, 'text': '<p>Ummm… An inner class <em>is</em> a nested class… Do you mean anonymous class and inner class?</p>\n<p>Edit: If you actually meant inner v.s. anonymous: an inner class is just a class defined within a class, such as:</p>\n<pre><code>public class A {\n    public class B {\n    }\n}\n</code></pre>\n<p>…whereas an anonymous class is an extension of a class defined anonymously, so no actual &quot;class&quot; is defined, as in:</p>\n<pre><code>public class A {\n}\n\nA anon = new A() { /* You could change behavior of A here */ };\n</code></pre>\n<p>Further edit:</p>\n<p>Wikipedia <a href="http://en.wikipedia.org/wiki/Inner_class" rel="nofollow noreferrer">claims there is a difference</a> in Java, but I\'ve been working with Java for eight years, and it\'s the first time I heard such a distinction – not to mention there are no references there to back up the claim… Bottom line, an inner class is a class defined within a class (static or not), and nested is just another term to mean the same thing.</p>\n<p>There is a subtle difference between static and non-static nested classes… Basically, non-static inner classes have implicit access to instance fields and methods of the enclosing class (thus they cannot be constructed in a static context, it will be a compiler error). On the other hand, static nested classes don\'t have implicit access to instance fields and methods and <em>can</em> be constructed in a static context.</p>\n'}, {'answer_id': 70349, 'author': 'Daniel Spiewak', 'author_id': 9815, 'author_profile': 'https://Stackoverflow.com/users/9815', 'pm_score': 3, 'selected': False, 'text': '<p>The terms are used interchangeably.  If you want to be really pedantic about it, then you <em>could</em> define "nested class" to refer to a static inner class, one which has no enclosing instance.  In code, you might have something like this:</p>\n\n<pre><code>public class Outer {\n    public class Inner {}\n\n    public static class Nested {}\n}\n</code></pre>\n\n<p>That\'s not really a widely accepted definition though.</p>\n'}, {'answer_id': 70358, 'author': 'Martin', 'author_id': 11357, 'author_profile': 'https://Stackoverflow.com/users/11357', 'pm_score': 12, 'selected': True, 'text': '<p>From the <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html" rel="noreferrer">Java Tutorial</a>:</p>\n\n<blockquote>\n  <p>Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. </p>\n</blockquote>\n\n<p>Static nested classes are accessed using the enclosing class name:</p>\n\n<pre><code>OuterClass.StaticNestedClass\n</code></pre>\n\n<p>For example, to create an object for the static nested class, use this syntax:</p>\n\n<pre><code>OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();\n</code></pre>\n\n<p>Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:</p>\n\n<pre><code>class OuterClass {\n    ...\n    class InnerClass {\n        ...\n    }\n}\n</code></pre>\n\n<p>An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.</p>\n\n<p>To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:</p>\n\n<pre><code>OuterClass outerObject = new OuterClass()\nOuterClass.InnerClass innerObject = outerObject.new InnerClass();\n</code></pre>\n\n<p>see: <a href="http://download.oracle.com/javase/tutorial/java/javaOO/nested.html" rel="noreferrer">Java Tutorial - Nested Classes</a></p>\n\n<p>For completeness note that there is also such a thing as an <a href="https://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance">inner class <em>without</em> an enclosing instance</a>:</p>\n\n<pre><code>class A {\n  int t() { return 1; }\n  static A a =  new A() { int t() { return 2; } };\n}\n</code></pre>\n\n<p>Here, <code>new A() { ... }</code> is an <em>inner class defined in a static context</em> and does not have an enclosing instance.</p>\n'}, {'answer_id': 70394, 'author': 'Wouter Coekaerts', 'author_id': 3432, 'author_profile': 'https://Stackoverflow.com/users/3432', 'pm_score': 3, 'selected': False, 'text': '<p>Nested class is a very general term: every class which is not top level is a nested class.\nAn inner class is a non-static nested class.\nJoseph Darcy wrote a very nice explanation about <a href="http://blogs.oracle.com/darcy/entry/nested_inner_member_and_top" rel="noreferrer">Nested, Inner, Member, and Top-Level Classes</a>.</p>\n'}, {'answer_id': 70522, 'author': 'rmaruszewski', 'author_id': 6856, 'author_profile': 'https://Stackoverflow.com/users/6856', 'pm_score': 4, 'selected': False, 'text': '<p>The instance of the inner class is created when instance of the outer class is created. Therefore the members and methods of the inner class have access to the members and methods of the instance (object) of the outer class. When the instance of the outer class goes out of scope, also the inner class instances cease to exist.</p>\n\n<p>The static nested class doesn\'t have a concrete instance. It\'s just loaded when it\'s used for the first time (just like the static methods). It\'s a completely independent entity, whose methods and variables doesn\'t have any access to the instances of the outer class.</p>\n\n<p>The static nested classes are not coupled with the outer object, they are faster, and they don\'t take heap/stack memory, because its not necessary to create instance of such class. Therefore the rule of thumb is to try to define static nested class, with as limited scope as possible (private >= class >= protected >= public), and then convert it to inner class (by removing "static" identifier) and loosen the scope, if it\'s really necessary.</p>\n'}, {'answer_id': 70613, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 7, 'selected': False, 'text': "<p>I don't think the real difference became clear in the above answers. </p>\n\n<p>First to get the terms right: </p>\n\n<ul>\n<li>A nested class is a class which is contained in another class at the source code level.</li>\n<li>It is static if you declare it with the <strong>static</strong> modifier.</li>\n<li>A non-static nested class is called inner class. (I stay with non-static nested class.)</li>\n</ul>\n\n<p>Martin's answer is right so far. However, the actual question is: What is the purpose of declaring a nested class static or not?</p>\n\n<p>You use <strong>static nested classes</strong> if you just want to keep your classes together if they belong topically together or if the nested class is exclusively used in the enclosing class. There is no semantic difference between a static nested class and every other class.</p>\n\n<p><strong>Non-static nested classes</strong> are a different beast. Similar to anonymous inner classes, such nested classes are actually closures. That means they capture their surrounding scope and their enclosing instance and make that accessible. Perhaps an example will clarify that. See this stub of a Container:</p>\n\n<pre><code>public class Container {\n    public class Item{\n        Object data;\n        public Container getContainer(){\n            return Container.this;\n        }\n        public Item(Object data) {\n            super();\n            this.data = data;\n        }\n\n    }\n\n    public static Item create(Object data){\n        // does not compile since no instance of Container is available\n        return new Item(data);\n    }\n    public Item createSubItem(Object data){\n        // compiles, since 'this' Container is available\n        return new Item(data);\n    }\n}\n</code></pre>\n\n<p>In this case you want to have a reference from a child item to the parent container. Using a non-static nested class, this works without some work. You can access the enclosing instance of Container with the syntax <code>Container.this</code>.</p>\n\n<p>More hardcore explanations following:</p>\n\n<p>If you look at the Java bytecodes the compiler generates for an (non-static) nested class it might become even clearer:</p>\n\n<pre><code>// class version 49.0 (49)\n// access flags 33\npublic class Container$Item {\n\n  // compiled from: Container.java\n  // access flags 1\n  public INNERCLASS Container$Item Container Item\n\n  // access flags 0\n  Object data\n\n  // access flags 4112\n  final Container this$0\n\n  // access flags 1\n  public getContainer() : Container\n   L0\n    LINENUMBER 7 L0\n    ALOAD 0: this\n    GETFIELD Container$Item.this$0 : Container\n    ARETURN\n   L1\n    LOCALVARIABLE this Container$Item L0 L1 0\n    MAXSTACK = 1\n    MAXLOCALS = 1\n\n  // access flags 1\n  public &lt;init&gt;(Container,Object) : void\n   L0\n    LINENUMBER 12 L0\n    ALOAD 0: this\n    ALOAD 1\n    PUTFIELD Container$Item.this$0 : Container\n   L1\n    LINENUMBER 10 L1\n    ALOAD 0: this\n    INVOKESPECIAL Object.&lt;init&gt;() : void\n   L2\n    LINENUMBER 11 L2\n    ALOAD 0: this\n    ALOAD 2: data\n    PUTFIELD Container$Item.data : Object\n    RETURN\n   L3\n    LOCALVARIABLE this Container$Item L0 L3 0\n    LOCALVARIABLE data Object L0 L3 2\n    MAXSTACK = 2\n    MAXLOCALS = 3\n}\n</code></pre>\n\n<p>As you can see the compiler creates a hidden field <code>Container this$0</code>. This is set in the constructor which has an additional parameter of type Container to specify the enclosing instance. You can't see this parameter in the source but the compiler implicitly generates it for a nested class. </p>\n\n<p>Martin's example</p>\n\n<pre><code>OuterClass.InnerClass innerObject = outerObject.new InnerClass();\n</code></pre>\n\n<p>would so be compiled to a call of something like (in bytecodes)</p>\n\n<pre><code>new InnerClass(outerObject)\n</code></pre>\n\n<p>For the sake of completeness:</p>\n\n<p>An anonymous class <strong>is</strong> a perfect example of a non-static nested class which just has no name associated with it and can't be referenced later.</p>\n"}, {'answer_id': 70687, 'author': 'Jegschemesch', 'author_id': 1586, 'author_profile': 'https://Stackoverflow.com/users/1586', 'pm_score': 9, 'selected': False, 'text': '<p>The <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html" rel="noreferrer">Java tutorial says</a>:</p>\n\n<blockquote>\n  <p>Terminology: Nested classes are\n  divided into two categories: static\n  and non-static. Nested classes that\n  are declared static are simply called\n  static nested classes. Non-static\n  nested classes are called inner\n  classes.</p>\n</blockquote>\n\n<p>In common parlance, the terms "nested" and "inner" are used interchangeably by most programmers, but I\'ll use the correct term "nested class" which covers both inner and static.</p>\n\n<p>Classes can be nested <em>ad infinitum</em>, e.g. class A can contain class B which contains class C which contains class D, etc. However, more than one level of class nesting is rare, as it is generally bad design.</p>\n\n<p>There are three reasons you might create a nested class:</p>\n\n<ul>\n<li>organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won\'t be used in any other context</li>\n<li>access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).</li>\n<li>convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context</li>\n</ul>\n\n<p>There are <strong>four kinds of nested class in Java</strong>. In brief, they are:</p>\n\n<ul>\n<li><strong>static class</strong>: declared as a static member of another class</li>\n<li><strong>inner class</strong>: declared as an instance member of another class</li>\n<li><strong>local inner class</strong>: declared inside an instance method of another class</li>\n<li><strong>anonymous inner class</strong>: like a local inner class, but written as an expression which returns a one-off object</li>\n</ul>\n\n<p>Let me elaborate in more details.</p>\n\n<p><br></p>\n\n<h2>Static Classes</h2>\n\n<p>Static classes are the easiest kind to understand because they have nothing to do with instances of the containing class.</p>\n\n<p>A static class is a class declared as a static member of another class. Just like other static members, such a class is really just a hanger on that uses the containing class as its namespace, <em>e.g.</em> the class <em>Goat</em> declared as a static member of class <em>Rhino</em> in the package <em>pizza</em> is known by the name <em>pizza.Rhino.Goat</em>.</p>\n\n<pre><code>package pizza;\n\npublic class Rhino {\n\n    ...\n\n    public static class Goat {\n        ...\n    }\n}\n</code></pre>\n\n<p>Frankly, static classes are a pretty worthless feature because classes are already divided into namespaces by packages. The only real conceivable reason to create a static class is that such a class has access to its containing class\'s private static members, but I find this to be a pretty lame justification for the static class feature to exist.</p>\n\n<p><br></p>\n\n<h2>Inner Classes</h2>\n\n<p>An inner class is a class declared as a non-static member of another class:</p>\n\n<pre><code>package pizza;\n\npublic class Rhino {\n\n    public class Goat {\n        ...\n    }\n\n    private void jerry() {\n        Goat g = new Goat();\n    }\n}\n</code></pre>\n\n<p>Like with a static class, the inner class is known as qualified by its containing class name, <em>pizza.Rhino.Goat</em>, but inside the containing class, it can be known by its simple name. However, every instance of an inner class is tied to a particular instance of its containing class: above, the <em>Goat</em> created in <em>jerry</em>, is implicitly tied to the <em>Rhino</em> instance <em>this</em> in <em>jerry</em>. Otherwise, we make the associated <em>Rhino</em> instance explicit when we instantiate <em>Goat</em>:</p>\n\n<pre><code>Rhino rhino = new Rhino();\nRhino.Goat goat = rhino.new Goat();\n</code></pre>\n\n<p>(Notice you refer to the inner type as just <em>Goat</em> in the weird <em>new</em> syntax: Java infers the containing type from the <em>rhino</em> part. And, yes <em>new rhino.Goat()</em> would have made more sense to me too.)</p>\n\n<p>So what does this gain us? Well, the inner class instance has access to the instance members of the containing class instance. These enclosing instance members are referred to inside the inner class <em>via</em> just their simple names, not <em>via</em> <em>this</em> (<em>this</em> in the inner class refers to the inner class instance, not the associated containing class instance): </p>\n\n<pre><code>public class Rhino {\n\n    private String barry;\n\n    public class Goat {\n        public void colin() {\n            System.out.println(barry);\n        }\n    }\n}\n</code></pre>\n\n<p>In the inner class, you can refer to <em>this</em> of the containing class as <em>Rhino.this</em>, and you can use <em>this</em> to refer to its members, <em>e.g. Rhino.this.barry</em>.</p>\n\n<p><br></p>\n\n<h2>Local Inner Classes</h2>\n\n<p>A local inner class is a class declared in the body of a method. Such a class is only known within its containing method, so it can only be instantiated and have its members accessed within its containing method. The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance\'s creation, even if the variable has gone out of scope (this is effectively Java\'s crude, limited version of closures).</p>\n\n<p>Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)</p>\n\n<p>If a local inner class is declared in an instance method, an instantiation of the inner class is tied to the instance held by the containing method\'s <em>this</em> at the time of the instance\'s creation, and so the containing class\'s instance members are accessible like in an instance inner class. A local inner class is instantiated simply <em>via</em> its name, <em>e.g.</em> local inner class <em>Cat</em> is instantiated as <em>new Cat()</em>, not new this.Cat() as you might expect.</p>\n\n<p><br></p>\n\n<h2>Anonymous Inner Classes</h2>\n\n<p>An anonymous inner class is a syntactically convenient way of writing a local inner class. Most commonly, a local inner class is instantiated at most just once each time its containing method is run. It would be nice, then, if we could combine the local inner class definition and its single instantiation into one convenient syntax form, and it would also be nice if we didn\'t have to think up a name for the class (the fewer unhelpful names your code contains, the better). An anonymous inner class allows both these things:</p>\n\n<pre><code>new *ParentClassName*(*constructorArgs*) {*members*}\n</code></pre>\n\n<p>This is an expression returning a new instance of an unnamed class which extends <em>ParentClassName</em>. You cannot supply your own constructor; rather, one is implicitly supplied which simply calls the super constructor, so the arguments supplied must fit the super constructor. (If the parent contains multiple constructors, the “simplest” one is called, “simplest” as determined by a rather complex set of rules not worth bothering to learn in detail--just pay attention to what NetBeans or Eclipse tell you.)</p>\n\n<p>Alternatively, you can specify an interface to implement:</p>\n\n<pre><code>new *InterfaceName*() {*members*}\n</code></pre>\n\n<p>Such a declaration creates a new instance of an unnamed class which extends Object and implements <em>InterfaceName</em>. Again, you cannot supply your own constructor; in this case, Java implicitly supplies a no-arg, do-nothing constructor (so there will never be constructor arguments in this case).</p>\n\n<p>Even though you can\'t give an anonymous inner class a constructor, you can still do any setup you want using an initializer block (a {} block placed outside any method).</p>\n\n<p>Be clear that an anonymous inner class is simply a less flexible way of creating a local inner class with one instance. If you want a local inner class which implements multiple interfaces or which implements interfaces while extending some class other than <em>Object</em> or which specifies its own constructor, you\'re stuck creating a regular named local inner class.</p>\n'}, {'answer_id': 2523233, 'author': 'HippoMan', 'author_id': 302506, 'author_profile': 'https://Stackoverflow.com/users/302506', 'pm_score': 4, 'selected': False, 'text': '<p>There is a subtlety about the use of nested static classes that might be useful in certain situations.</p>\n\n<p>Whereas static attributes get instantiated before the class gets instantiated via its constructor,\nstatic attributes inside of nested static classes don\'t seem to get instantiated until after the\nclass\'s constructor gets invoked, or at least not until after the attributes are first referenced,\neven if they are marked as \'final\'.</p>\n\n<p>Consider this example:</p>\n\n<pre><code>public class C0 {\n\n    static C0 instance = null;\n\n    // Uncomment the following line and a null pointer exception will be\n    // generated before anything gets printed.\n    //public static final String outerItem = instance.makeString(98.6);\n\n    public C0() {\n        instance = this;\n    }\n\n    public String makeString(int i) {\n        return ((new Integer(i)).toString());\n    }\n\n    public String makeString(double d) {\n        return ((new Double(d)).toString());\n    }\n\n    public static final class nested {\n        public static final String innerItem = instance.makeString(42);\n    }\n\n    static public void main(String[] argv) {\n        System.out.println("start");\n        // Comment out this line and a null pointer exception will be\n        // generated after "start" prints and before the following\n        // try/catch block even gets entered.\n        new C0();\n        try {\n            System.out.println("retrieve item: " + nested.innerItem);\n        }\n        catch (Exception e) {\n            System.out.println("failed to retrieve item: " + e.toString());\n        }\n        System.out.println("finish");\n    }\n}\n</code></pre>\n\n<p>Even though \'nested\' and \'innerItem\' are both declared as \'static final\'. the setting\nof nested.innerItem doesn\'t take place until after the class is instantiated (or at least\nnot until after the nested static item is first referenced), as you can see for yourself\nby commenting and uncommenting the lines that I refer to, above. The same does not hold\ntrue for \'outerItem\'.</p>\n\n<p>At least this is what I\'m seeing in Java 6.0.</p>\n'}, {'answer_id': 2574123, 'author': 'tejas', 'author_id': 308651, 'author_profile': 'https://Stackoverflow.com/users/308651', 'pm_score': 4, 'selected': False, 'text': '<p>Nested class: class inside class</p>\n\n<p>Types:</p>\n\n<ol>\n<li>Static nested class</li>\n<li>Non-static nested class [Inner class]</li>\n</ol>\n\n<p>Difference:</p>\n\n<p><strong>Non-static nested class [Inner class]</strong></p>\n\n<p>In non-static nested class object of inner class exist within object of outer class. So that data member of outer class is accessible to inner class. So to create object of inner class we must create object of outer class first.</p>\n\n<pre><code>outerclass outerobject=new outerobject();\nouterclass.innerclass innerobjcet=outerobject.new innerclass(); \n</code></pre>\n\n<p><strong>Static nested class</strong></p>\n\n<p>In static nested class object of inner class don\'t need object of outer class, because the word "static" indicate no need to create object.</p>\n\n<pre><code>class outerclass A {\n    static class nestedclass B {\n        static int x = 10;\n    }\n}\n</code></pre>\n\n<p>If you want to access x, then write the following inside method</p>\n\n<pre><code>  outerclass.nestedclass.x;  i.e. System.out.prinltn( outerclass.nestedclass.x);\n</code></pre>\n'}, {'answer_id': 4460365, 'author': 'sactiw', 'author_id': 416369, 'author_profile': 'https://Stackoverflow.com/users/416369', 'pm_score': 5, 'selected': False, 'text': '<p>I think, the convention that is generally followed is this:</p>\n\n<ul>\n<li><strong>static class</strong> within a top level class is a <strong>nested class</strong></li>\n<li><strong>non static class</strong> within a top level  class is a <strong>inner class</strong>, which further\nhas two more form:\n<ul>\n<li><strong>local class</strong> - named classes declared inside of a block like a method or constructor body</li>\n<li><strong>anonymous class</strong> - unnamed classes whose instances are created in expressions and statements</li>\n</ul></li>\n</ul>\n\n<p>However, few other <strong>points to remembers</strong> are:</p>\n\n<ul>\n<li><p>Top level classes and static nested class are semantically same except that in case of static nested class it can make static reference to private static fields/methods of its Outer [parent] class and vice versa.</p></li>\n<li><p>Inner classes have access to instance variables of the enclosing instance of the Outer [parent] class. However, not all inner classes have enclosing instances, for example inner classes in static contexts, like an anonymous class used in a static initializer block, do not.</p></li>\n<li><p>Anonymous class by default extends the parent class or implements the parent interface and there is no further clause to extend any other class or implement any more interfaces. So,</p>\n\n<ul>\n<li><code>new YourClass(){};</code>       means   <code>class [Anonymous] extends YourClass {}</code></li>\n<li><code>new YourInterface(){};</code>   means   <code>class [Anonymous] implements YourInterface {}</code></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>I feel that the bigger question that remains open which one to use and when? Well that mostly depends on what scenario you are dealing with but reading the reply given by @jrudolph may help you making some decision.</p>\n'}, {'answer_id': 9904357, 'author': 'hqt', 'author_id': 1192728, 'author_profile': 'https://Stackoverflow.com/users/1192728', 'pm_score': 2, 'selected': False, 'text': "<p>I think people here should notice to Poster that : Static Nest Class just only the first inner class.\nFor example:</p>\n\n<pre><code> public static class A {} //ERROR\n\n public class A {\n     public class B {\n         public static class C {} //ERROR\n     }\n }\n\n public class A {\n     public static class B {} //COMPILE !!!\n\n }\n</code></pre>\n\n<p>So, summarize, static class doesn't depend which class its contains. So, they cannot in normal class. (because normal class need an instance).</p>\n"}, {'answer_id': 10772428, 'author': 'aleroot', 'author_id': 330280, 'author_profile': 'https://Stackoverflow.com/users/330280', 'pm_score': 7, 'selected': False, 'text': "<p>I think that none of the above answers explain to you the real difference between a nested class and a static nested class in term of application design : </p>\n\n<h2>OverView</h2>\n\n<p><strong>A nested class</strong> could be nonstatic or static and in each case <strong>is a class defined within another class</strong>. <strong>A nested class should exist only to serve is enclosing class</strong>, if a nested class is useful by other classes (not only the enclosing), should be declared as a top level class.</p>\n\n<h2>Difference</h2>\n\n<p><strong>Nonstatic Nested class</strong> : is implicitly associated with the enclosing instance of the containing class, this means that it is possible to invoke methods and access variables of the enclosing instance. One common use of a nonstatic nested class is to define an Adapter class.</p>\n\n<p><strong>Static Nested Class</strong> : can't access enclosing class instance and invoke methods on it, so should be used when the nested class doesn't require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.</p>\n\n<h2>Conclusion</h2>\n\n<p>So the main difference between the two from a design standpoint is : <em>nonstatic nested class can access instance of the container class, while static can't</em>.</p>\n"}, {'answer_id': 18721137, 'author': 'Sohi', 'author_id': 1802850, 'author_profile': 'https://Stackoverflow.com/users/1802850', 'pm_score': 0, 'selected': False, 'text': '<p>First of all There is no such class called Static class.The Static modifier use with inner class (called as Nested Class) says that it is a static member of Outer Class which means we can access it as with other static members and without having any instance of Outer class. (Which is benefit of static originally.) </p>\n\n<p>Difference between using Nested class and regular Inner class is:</p>\n\n<pre><code>OuterClass.InnerClass inner = new OuterClass().new InnerClass();\n</code></pre>\n\n<p>First We can to instantiate Outerclass then we Can access Inner.</p>\n\n<p>But if Class is Nested then syntax is:</p>\n\n<pre><code>OuterClass.InnerClass inner = new OuterClass.InnerClass();\n</code></pre>\n\n<p>Which uses the static Syntax as normal implementation of static keyword.</p>\n'}, {'answer_id': 19438489, 'author': 'Thalaivar', 'author_id': 337128, 'author_profile': 'https://Stackoverflow.com/users/337128', 'pm_score': 5, 'selected': False, 'text': "<p>In simple terms we need nested classes primarily because Java does not provide closures.</p>\n\n<p>Nested Classes are classes defined inside the body of another enclosing class. They are of two types - static and non-static.</p>\n\n<p>They are treated as members of the enclosing class, hence you can specify any of the four access specifiers - <code>private, package, protected, public</code>. We don't have this luxury with top-level classes, which can only be declared <code>public</code> or package-private.</p>\n\n<p>Inner classes aka Non-stack classes have access to other members of the top class, even if they are declared private while Static nested classes do not have access to other members of the top class.</p>\n\n<pre><code>public class OuterClass {\n    public static class Inner1 {\n    }\n    public class Inner2 {\n    }\n}\n</code></pre>\n\n<p><code>Inner1</code> is our static inner class and <code>Inner2</code> is our inner class which is not static. The key difference between them, you can't create an <code>Inner2</code> instance without an Outer where as you can create an <code>Inner1</code> object independently.</p>\n\n<p>When would you use Inner class?</p>\n\n<p>Think of a situation where <code>Class A</code> and <code>Class B</code> are related, <code>Class B</code> needs to access <code>Class A</code> members, and <code>Class B</code> is related only to <code>Class A</code>. Inner classes comes into the picture.</p>\n\n<p>For creating an instance of inner class, you need to create an instance of your outer class.</p>\n\n<pre><code>OuterClass outer = new OuterClass();\nOuterClass.Inner2 inner = outer.new Inner2();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>OuterClass.Inner2 inner = new OuterClass().new Inner2();\n</code></pre>\n\n<p>When would you use static Inner class?</p>\n\n<p>You would define a static inner class when you know that it does not have any relationship with the instance of the enclosing class/top class. If your inner class doesn't use methods or fields of the outer class, it's just a waste of space, so make it static.</p>\n\n<p>For example, to create an object for the static nested class, use this syntax:</p>\n\n<pre><code>OuterClass.Inner1 nestedObject = new OuterClass.Inner1();\n</code></pre>\n\n<p>The advantage of a static nested class is that it doesn't need an object of the containing class/top class to work. This can help you to reduce the number of objects your application creates at runtime.</p>\n"}, {'answer_id': 19977690, 'author': 'Ankit Jain', 'author_id': 1423581, 'author_profile': 'https://Stackoverflow.com/users/1423581', 'pm_score': 3, 'selected': False, 'text': '<p>In the case of creating instance, the instance of non \nstatic inner class is created with the reference of\nobject of outer class in which it is defined. This\nmeans it have inclosing instance.\nBut the instance of static inner class\nis created with the reference of Outer class, not with\nthe reference of object of outer class. This means it\nhave not inclosing instance.</p>\n\n<p>For example:</p>\n\n<pre><code>class A\n{\n  class B\n  {\n    // static int x; not allowed here…..    \n  }\n  static class C\n  {\n    static int x; // allowed here\n  }\n}\n\nclass Test\n{\n  public static void main(String… str)\n  {\n    A o=new A();\n    A.B obj1 =o.new B();//need of inclosing instance\n\n    A.C obj2 =new A.C();\n\n    // not need of reference of object of outer class….\n  }\n}\n</code></pre>\n'}, {'answer_id': 31537275, 'author': 'VeKe', 'author_id': 1878022, 'author_profile': 'https://Stackoverflow.com/users/1878022', 'pm_score': 3, 'selected': False, 'text': '<p><em>Targeting learner, who are novice to Java and/or Nested Classes</em>  </p>\n\n<p>Nested classes can be either:\n<br> 1. Static Nested classes.<br>\n 2. Non Static Nested classes. (also known as <strong>Inner classes</strong>) =>Please remember this<br></p>\n\n<p><br>\n<strong>1.Inner classes</strong><br>\nExample:</p>\n\n<pre><code>class OuterClass  {\n/*  some code here...*/\n     class InnerClass  {  }\n/*  some code here...*/\n}\n</code></pre>\n\n<p><br><strong>Inner classes are subsets of nested classes:</strong></p>\n\n<ul>\n<li>inner class is a specific type of nested class</li>\n<li>inner classes are subsets of nested classes</li>\n<li>You can say that an <em>inner class is also a nested class, but you can <strong>NOT</strong> say that a nested class is also an inner class</em>.  </li>\n</ul>\n\n<p><strong>Specialty of Inner class:</strong></p>\n\n<ul>\n<li>instance of an inner class has <strong>access to all</strong> of the members of the outer class, even those that are marked “private”</li>\n</ul>\n\n<p><br>\n<strong>2.Static Nested Classes:</strong><br>\nExample:</p>\n\n<pre><code>class EnclosingClass {\n  static class Nested {\n    void someMethod() { System.out.println("hello SO"); }\n  }\n}\n</code></pre>\n\n<p><strong>Case 1:Instantiating a static nested class from a non-enclosing class</strong></p>\n\n<pre><code>class NonEnclosingClass {\n\n  public static void main(String[] args) {\n    /*instantiate the Nested class that is a static\n      member of the EnclosingClass class:\n    */\n\n    EnclosingClass.Nested n = new EnclosingClass.Nested(); \n    n.someMethod();  //prints out "hello"\n  }\n}\n</code></pre>\n\n<p><strong>Case 2:Instantiating a static nested class from an enclosing class</strong></p>\n\n<pre><code>class EnclosingClass {\n\n  static class Nested {\n    void anotherMethod() { System.out.println("hi again"); } \n  }\n\n  public static void main(String[] args) {\n    //access enclosed class:\n\n    Nested n = new Nested(); \n    n.anotherMethod();  //prints out "hi again"\n  }\n\n}\n</code></pre>\n\n<p><strong>Specialty of Static classes:</strong></p>\n\n<ul>\n<li>Static inner class would only have access to the static members of the outer class, and have no access to non-static members.</li>\n</ul>\n\n<p><strong>Conclusion:</strong><br>\n<em>Question:</em> What is the main difference between a inner class and a static nested class in Java?<br>\n<em>Answer:</em> just go through specifics of each class mentioned above.</p>\n'}, {'answer_id': 33781508, 'author': 'Adelin', 'author_id': 1170677, 'author_profile': 'https://Stackoverflow.com/users/1170677', 'pm_score': 3, 'selected': False, 'text': '<p>I don\'t think there is much to add here, most of the answers perfectly explain the differences between static nested class and Inner classes. However, consider the following issue when using nested classes vs inner classes. \nAs mention in a couple of answers inner classes can not be instantiated without and instance of their enclosing class which mean that they <strong>HOLD</strong> a <strong>pointer</strong> to the instance of their enclosing class which can lead to memory overflow or stack overflow exception due to the fact the GC will not be able to garbage collect the enclosing classes even if they are not used any more. To make this clear check the following code out: </p>\n\n<pre><code>public class Outer {\n\n\n    public  class Inner {\n\n    }\n\n\n    public Inner inner(){\n        return new Inner();\n    }\n\n    @Override\n    protected void finalize() throws Throwable {\n    // as you know finalize is called by the garbage collector due to destroying an object instance\n        System.out.println("I am destroyed !");\n    }\n}\n\n\npublic static void main(String arg[]) {\n\n    Outer outer = new Outer();\n    Outer.Inner inner = outer.new Inner();\n\n    // out instance is no more used and should be garbage collected !!!\n    // However this will not happen as inner instance is still alive i.e used, not null !\n    // and outer will be kept in memory until inner is destroyed\n    outer = null;\n\n    //\n    // inner = null;\n\n    //kick out garbage collector\n    System.gc();\n\n}\n</code></pre>\n\n<p>If you remove the comment on <code>// inner = null;</code> The program will out put \n"<strong>I am destroyed !</strong>", but keeping this commented it will not.<br>\nThe reason is that white inner instance is still referenced GC cannot collect it and because it references (has a pointer to) the outer instance it is not collected too. Having enough of these objects in your project and can run out of memory.<br>\nCompared to static inner classes which does not hold a point to inner class instance because it is not instance related but class related. \nThe above program can print "<strong>I am destroyed !</strong>" if you make Inner class static and instantiated with <code>Outer.Inner i = new Outer.Inner();</code>  </p>\n'}, {'answer_id': 34551507, 'author': 'Behzad Bahmanyar', 'author_id': 5079879, 'author_profile': 'https://Stackoverflow.com/users/5079879', 'pm_score': 5, 'selected': False, 'text': '<p>Here is key differences and similarities between Java inner class and static nested class.</p>\n\n<p>Hope it helps!</p>\n\n<h3>Inner class</h3>\n\n<ul>\n<li><strong>Can access</strong> to outer class <strong>both instance and static</strong> methods and fields</li>\n<li><p><strong>Associated with instance of enclosing class</strong> so to instantiate it first needs an instance of outer class (note <em>new</em> keyword place):</p>\n\n<pre><code>Outerclass.InnerClass innerObject = outerObject.new Innerclass();\n</code></pre></li>\n<li><p><strong>Cannot</strong> define any <strong>static members</strong> itself</p></li>\n<li><strong>Cannot</strong> have <strong>Class</strong> or <strong>Interface</strong> declaration</li>\n</ul>\n\n<h3>Static nested class</h3>\n\n<ul>\n<li><p><strong>Cannot access</strong> outer class <strong>instance</strong> methods or fields</p></li>\n<li><p><strong>Not associated with any instance of enclosing class</strong> So to instantiate it:</p>\n\n<pre><code>OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();\n</code></pre></li>\n</ul>\n\n<h3>Similarities</h3>\n\n<ul>\n<li>Both <strong>Inner classes</strong> can access even <strong>private fields and methods</strong> of <strong>outer class</strong></li>\n<li>Also the <strong>Outer class</strong> have access to <strong>private fields and methods</strong> of <strong>inner classes</strong></li>\n<li>Both classes can have private, protected or public access modifier</li>\n</ul>\n\n<h3>Why Use Nested Classes?</h3>\n\n<p>According to Oracle documentation there\'re several reasons (<a href="https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html" rel="noreferrer">full documentation</a>):</p>\n\n<blockquote>\n  <ul>\n  <li><p><strong>It is a way of logically grouping classes that are only used in one place:</strong> If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.</p></li>\n  <li><p><strong>It increases encapsulation:</strong> Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A\'s members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.</p></li>\n  <li><p><strong>It can lead to more readable and maintainable code:</strong> Nesting small classes within top-level classes places the code closer to where it is used.</p></li>\n  </ul>\n</blockquote>\n'}, {'answer_id': 39669941, 'author': 'DigitalRoss', 'author_id': 140740, 'author_profile': 'https://Stackoverflow.com/users/140740', 'pm_score': -1, 'selected': False, 'text': "<p>The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.</p>\n\n<p>When you have a nested class declaration that is <em>not</em> static, also known as an <em>inner class</em>, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.</p>\n\n<p>But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.</p>\n"}, {'answer_id': 40937372, 'author': 'Pankti', 'author_id': 5095067, 'author_profile': 'https://Stackoverflow.com/users/5095067', 'pm_score': 2, 'selected': False, 'text': '<p>When we declare static member class inside a class, it is known as top level nested class or a static nested class. It can be demonstrated as below : </p>\n\n<pre><code>class Test{\n    private static int x = 1;\n        static class A{\n        private static int y = 2;\n        public static int getZ(){\n            return B.z+x;\n        }\n    }\n    static class B{\n        private static int z = 3;\n        public static int getY(){\n            return A.y;\n        }\n    }\n}\n\nclass TestDemo{\n     public static void main(String[] args){\n        Test t = new Test();\n        System.out.println(Test.A.getZ());\n        System.out.println(Test.B.getY());\n    }\n}\n</code></pre>\n\n<p>When we declare non-static member class inside a class it is known as inner class. Inner class can be demonstrated as below : </p>\n\n<pre><code>    class Test{\n        private int i = 10;\n        class A{\n            private int i =20;\n            void display(){\n            int i = 30;\n            System.out.println(i);\n            System.out.println(this.i);\n            System.out.println(Test.this.i);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 41453771, 'author': 'Pritam Banerjee', 'author_id': 1475228, 'author_profile': 'https://Stackoverflow.com/users/1475228', 'pm_score': 2, 'selected': False, 'text': '<p>The following is an example of <code>static nested class</code> and <code>inner class</code>:</p>\n\n<p><strong>OuterClass.java</strong></p>\n\n<pre><code>public class OuterClass {\n     private String someVariable = "Non Static";\n\n     private static String anotherStaticVariable = "Static";  \n\n     OuterClass(){\n\n     }\n\n     //Nested classes are static\n     static class StaticNestedClass{\n        private static String privateStaticNestedClassVariable = "Private Static Nested Class Variable"; \n\n        //can access private variables declared in the outer class\n        public static void getPrivateVariableofOuterClass(){\n            System.out.println(anotherStaticVariable);\n        }\n     }\n\n     //non static\n     class InnerClass{\n\n         //can access private variables of outer class\n         public String getPrivateNonStaticVariableOfOuterClass(){\n             return someVariable;\n         }\n     }\n\n     public static void accessStaticClass(){\n         //can access any variable declared inside the Static Nested Class \n         //even if it private\n         String var = OuterClass.StaticNestedClass.privateStaticNestedClassVariable; \n         System.out.println(var);\n     }\n\n}\n</code></pre>\n\n<p><strong>OuterClassTest:</strong></p>\n\n<pre><code>public class OuterClassTest {\n    public static void main(String[] args) {\n\n        //access the Static Nested Class\n        OuterClass.StaticNestedClass.getPrivateVariableofOuterClass();\n\n        //test the private variable declared inside the static nested class\n        OuterClass.accessStaticClass();\n        /*\n         * Inner Class Test\n         * */\n\n        //Declaration\n\n        //first instantiate the outer class\n        OuterClass outerClass = new OuterClass();\n\n        //then instantiate the inner class\n        OuterClass.InnerClass innerClassExample =  outerClass. new InnerClass();\n\n        //test the non static private variable\n        System.out.println(innerClassExample.getPrivateNonStaticVariableOfOuterClass()); \n\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 42949189, 'author': 'roottraveller', 'author_id': 5167682, 'author_profile': 'https://Stackoverflow.com/users/5167682', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Inner class</strong> and <strong>nested static class</strong> in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non static nested class are simply referred as Inner Class. </p>\n\n<p><strong>What is Inner Class in Java?</strong></p>\n\n<p>Any class which is not a top level or declared inside another class is known as nested class and out of those nested classes, class which are declared non static are known as Inner class in Java. there are three kinds of Inner class in Java:</p>\n\n<p>1) Local inner class    - is declared inside a code block or method.<br>\n2) Anonymous inner class - is a class which doesn\'t have name to reference and initialized at same place where it gets created.<br>\n3) Member inner class - is declared as non static member of outer class.</p>\n\n<pre><code>public class InnerClassTest {\n    public static void main(String args[]) {      \n        //creating local inner class inside method i.e. main() \n        class Local {\n            public void name() {\n                System.out.println("Example of Local class in Java");\n\n            }\n        }      \n        //creating instance of local inner class\n        Local local = new Local();\n        local.name(); //calling method from local inner class\n\n        //Creating anonymous inner class in Java for implementing thread\n        Thread anonymous = new Thread(){\n            @Override\n            public void run(){\n                System.out.println("Anonymous class example in java");\n            }\n        };\n        anonymous.start();\n\n        //example of creating instance of inner class\n        InnerClassTest test = new InnerClassTest();\n        InnerClassTest.Inner inner = test.new Inner();\n        inner.name(); //calling method of inner class\n    }\n\n     //Creating Inner class in Java\n    private class Inner{\n        public void name(){\n            System.out.println("Inner class example in java");\n        }\n    }\n}\n</code></pre>\n\n<p><strong>What is nested static class in Java?</strong></p>\n\n<p>Nested static class is another class which is declared inside a class as member and made static. Nested static class is also declared as member of outer class and can be make private, public or protected like any other member. One of the main benefit of nested static class over inner class is that instance of nested static class is not attached to any enclosing instance of Outer class. <em>You also don\'t need any instance of Outer class to create instance of nested static class in Java</em>.</p>\n\n<p>1) It can access <em>static data members</em> of outer class including private.<br>\n2) Static nested class cannot access <em>non-static (instance) data member</em> or <em>method</em>.</p>\n\n<pre><code>public class NestedStaticExample {\n    public static void main(String args[]){  \n        StaticNested nested = new StaticNested();\n        nested.name();\n    }  \n    //static nested class in java\n    private static class StaticNested{\n        public void name(){\n            System.out.println("static nested class example in java");\n        }\n    }\n}\n</code></pre>\n\n<p>Ref: <a href="http://javarevisited.blogspot.in/2012/12/inner-class-and-nested-static-class-in-java-difference.html" rel="noreferrer">Inner class and nested Static Class in Java with Example</a></p>\n'}, {'answer_id': 46664397, 'author': 'Ashish Sharma', 'author_id': 7503961, 'author_profile': 'https://Stackoverflow.com/users/7503961', 'pm_score': -1, 'selected': False, 'text': '<p>I have illustrated various possible correct and error scenario which can occur in java code.</p>\n\n<pre><code>    class Outter1 {\n\n        String OutStr;\n\n        Outter1(String str) {\n            OutStr = str;\n        }\n\n        public void NonStaticMethod(String st)  {\n\n            String temp1 = "ashish";\n            final String  tempFinal1 = "ashish"; \n\n            //  below static attribute not permitted\n            // static String tempStatic1 = "static";    \n\n            //  below static with final attribute not permitted         \n            // static final String  tempStatic1 = "ashish";  \n\n            // synchronized keyword is not permitted below          \n            class localInnerNonStatic1 {            \n\n                synchronized    public void innerMethod(String str11) {\n                    str11 = temp1 +" sharma";\n                    System.out.println("innerMethod ===&gt; "+str11);\n                }\n\n                /* \n        //  static method with final not permitted\n          public static void innerStaticMethod(String str11) { \n\n                    str11 = temp1 +" india";\n                    System.out.println("innerMethod ===&gt; "+str11);\n                }*/\n            }\n\n            // static class not permitted below\n            //  static class localInnerStatic1 {   }                            \n\n        }\n\n        public static  void StaticMethod(String st)     {\n\n            String temp1 = "ashish";\n            final String  tempFinal1 = "ashish"; \n\n            // static attribute not permitted below\n            //static String tempStatic1 = "static";     \n\n            //  static with final attribute not permitted below\n            // static final String  tempStatic1 = "ashish";                         \n\n            class localInnerNonStatic1 {\n                public void innerMethod(String str11) {\n                    str11 = temp1 +" sharma";\n                    System.out.println("innerMethod ===&gt; "+str11);\n                }\n\n                /*\n    // static method with final not permitted\n    public static void innerStaticMethod(String str11) {  \n                    str11 = temp1 +" india";\n                    System.out.println("innerMethod ===&gt; "+str11);\n                }*/\n            }\n\n            // static class not permitted below\n            //  static class localInnerStatic1 {   }    \n\n        }\n\n        // synchronized keyword is not permitted\n        static  class inner1 {          \n\n            static String  temp1 = "ashish";\n            String  tempNonStatic = "ashish";\n            // class localInner1 {\n\n            public void innerMethod(String str11) {\n                str11 = temp1 +" sharma";\n                str11 = str11+ tempNonStatic +" sharma";\n                System.out.println("innerMethod ===&gt; "+str11);\n            }\n\n            public static void innerStaticMethod(String str11) {\n                //  error in below step\n                str11 = temp1 +" india";    \n                //str11 = str11+ tempNonStatic +" sharma";\n                System.out.println("innerMethod ===&gt; "+str11);\n            }\n            //}\n        }\n\n        //synchronized keyword is not permitted below\n        class innerNonStatic1 {             \n\n//This is important we have to keep final with static modifier in non\n// static innerclass below\n            static final String  temp1 = "ashish";  \n            String  tempNonStatic = "ashish";\n            // class localInner1 {\n\n            synchronized    public void innerMethod(String str11) {\n                tempNonStatic = tempNonStatic +" ...";\n                str11 = temp1 +" sharma";\n                str11 = str11+ tempNonStatic +" sharma";\n                System.out.println("innerMethod ===&gt; "+str11);\n            }\n\n            /*\n            //  error in below step\n            public static void innerStaticMethod(String str11) {   \n                            //  error in below step\n                            // str11 = tempNonStatic +" india";                     \n                            str11 = temp1 +" india";\n                            System.out.println("innerMethod ===&gt; "+str11);\n                        }*/\n                    //}\n                }\n    }\n</code></pre>\n'}, {'answer_id': 53737273, 'author': 'Mithun Debnath', 'author_id': 4046145, 'author_profile': 'https://Stackoverflow.com/users/4046145', 'pm_score': 1, 'selected': False, 'text': '<p>The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:</p>\n\n<pre><code>class OuterClass {\n...\nclass NestedClass {\n    ...\n    }\n}\n</code></pre>\n\n<p>Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.\nOne thing that we should keep in mind is Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes only have access to other members of the enclosing class if those are static. It can not access non static members of the outer class.\nAs with class methods and variables, a static nested class is associated with its outer class. \nFor example, to create an object for the static nested class, use this syntax:</p>\n\n<pre><code>OuterClass.StaticNestedClass nestedObject =\n new OuterClass.StaticNestedClass(); \n</code></pre>\n\n<p>To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:</p>\n\n<pre><code>OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();\n</code></pre>\n\n<p>Why we use nested classes</p>\n\n<ol>\n<li>It is a way of logically grouping classes that are only used in one place.</li>\n<li>It increases encapsulation.</li>\n<li>It can lead to more readable and maintainable code.</li>\n</ol>\n\n<p>Source: <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html" rel="nofollow noreferrer">The Java™ Tutorials - Nested Classes</a></p>\n'}, {'answer_id': 55014075, 'author': 'Leogao', 'author_id': 10312263, 'author_profile': 'https://Stackoverflow.com/users/10312263', 'pm_score': 3, 'selected': False, 'text': '<p>I think that none of the above answers give the real example to you the difference between a nested class and a static nested class in term of application design. And the main difference between static nested class and inner class is the ability to access the outer class instance field. </p>\n\n<p>Let us take a look at the two following examples.</p>\n\n<p>Static nest class: An good example of using static nested classes is builder pattern (<a href="https://dzone.com/articles/design-patterns-the-builder-pattern" rel="noreferrer">https://dzone.com/articles/design-patterns-the-builder-pattern</a>).</p>\n\n<p>For BankAccount we use a static nested class, mainly because </p>\n\n<ol>\n<li><p>Static nest class instance could be created before the outer class.</p></li>\n<li><p>In the builder pattern, the builder is a helper class which is used to create the BankAccount.</p></li>\n<li>BankAccount.Builder is only associated with BankAccount. No other classes are related to BankAccount.Builder. so it is better to organize them together without using name convention.</li>\n</ol>\n\n<pre class="lang-java prettyprint-override"><code>public class BankAccount {\n\n    private long accountNumber;\n    private String owner;\n    ...\n\n    public static class Builder {\n\n    private long accountNumber;\n    private String owner;\n    ...\n\n    static public Builder(long accountNumber) {\n        this.accountNumber = accountNumber;\n    }\n\n    public Builder withOwner(String owner){\n        this.owner = owner;\n        return this; \n    }\n\n    ...\n    public BankAccount build(){\n            BankAccount account = new BankAccount(); \n            account.accountNumber = this.accountNumber;\n            account.owner = this.owner;\n            ...\n            return account;\n        }\n    }\n}\n\n</code></pre>\n\n<p>Inner class: A common use of inner classes is to define an event handler.\n<a href="https://docs.oracle.com/javase/tutorial/uiswing/events/generalrules.html" rel="noreferrer">https://docs.oracle.com/javase/tutorial/uiswing/events/generalrules.html</a></p>\n\n<p>For MyClass, we use the inner class, mainly because: </p>\n\n<ol>\n<li><p>Inner class MyAdapter need to access the outer class member.</p></li>\n<li><p>In the example, MyAdapter is only associated with MyClass. No other classes are related to MyAdapter. so it is better to organize them together without using a name convention</p></li>\n</ol>\n\n<pre class="lang-java prettyprint-override"><code>public class MyClass extends Applet {\n    ...\n        someObject.addMouseListener(new MyAdapter());\n    ...\n    class MyAdapter extends MouseAdapter {\n        public void mouseClicked(MouseEvent e) {\n            ...// Event listener implementation goes here...\n            ...// change some outer class instance property depend on the event\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 59220181, 'author': 'yoAlex5', 'author_id': 4770877, 'author_profile': 'https://Stackoverflow.com/users/4770877', 'pm_score': 3, 'selected': False, 'text': '<p>A diagram</p>\n\n<p><a href="https://i.stack.imgur.com/4zgFn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4zgFn.png" alt="enter image description here"></a></p>\n\n<p>The main difference between <code>static nested</code> and <code>non-static nested</code> classes is that <code>static nested</code> <strong>does not have</strong> an access to non-static outer class members</p>\n'}, {'answer_id': 67084223, 'author': 'JCvanDamme', 'author_id': 4275167, 'author_profile': 'https://Stackoverflow.com/users/4275167', 'pm_score': 0, 'selected': False, 'text': "<p>Another use case for nested classes, in addition to those that already have been mentioned, is when the nested class has methods that should only be accessible from the outer class. This is possible because the outer class has access to the private constructors, fields and methods of the nested class.</p>\n<p>In the example below, the <code>Bank</code> can issue a <code>Bank.CreditCard</code>, which has a private constructor, and can change a credit card's limit according to the current bank policy using the private <code>setLimit(...)</code> instance method of <code>Bank.CreditCard</code>. (A direct field access to the instance variable <code>limit</code> would also work in this case). From any other class only the public methods of <code>Bank.CreditCard</code> are accessible.</p>\n<pre><code>public class Bank {\n\n    // maximum limit as per current bank policy\n    // is subject to change\n    private int maxLimit = 7000;\n\n    // ------- PUBLIC METHODS ---------\n\n    public CreditCard issueCard(\n            final String firstName,\n            final String lastName\n    ) {\n        final String number = this.generateNumber();\n        final int expiryDate = this.generateExpiryDate();\n        final int CVV = this.generateCVV();\n        return new CreditCard(firstName, lastName, number, expiryDate, CVV);\n    }\n\n\n    public boolean setLimit(\n            final CreditCard creditCard,\n            final int limit\n    ) {\n        if (limit &lt;= this.maxLimit) {    // check against current bank policy limit\n            creditCard.setLimit(limit);  // access private method Bank.CreditCard.setLimit(int)\n            return true;\n        }\n        return false;\n    }\n\n    // ------- PRIVATE METHODS ---------\n\n    private String generateNumber() {\n        return &quot;1234-5678-9101-1123&quot;;   // the numbers should be unique for each card\n    }\n\n\n    private int generateExpiryDate() {\n        return 202405;                  // date is YYYY=2024, MM=05\n    }\n\n\n    private int generateCVV() {\n        return 123;                     // is in real-life less predictable\n    }\n\n\n    // ------- PUBLIC STATIC NESTED CLASS ---------\n\n    public static final class CreditCard {\n        private final String firstName;\n        private final String lastName;\n        private final String number;\n        private final int expiryDate;\n        private final int CVV;\n\n        private int balance;\n        private int limit = 100; // default limit\n\n        // the constructor is final but is accessible from outer class\n        private CreditCard(\n                final String firstName,\n                final String lastName,\n                final String number,\n                final int expiryDate,\n                final int CVV\n        ) {\n            this.firstName = firstName;\n            this.lastName = lastName;\n            this.number = number;\n            this.expiryDate = expiryDate;\n            this.CVV = CVV;\n        }\n\n        // ------- PUBLIC METHODS ---------\n\n        public String getFirstName() {\n            return this.firstName;\n        }\n\n        public String getLastName() {\n            return this.lastName;\n        }\n\n        public String getNumber() {\n            return this.number;\n        }\n\n        public int getExpiryDate() {\n            return this.expiryDate;\n        }\n\n        // returns true if financial transaction is successful\n        // otherwise false\n        public boolean charge(final int amount) {\n            final int newBalance = this.balance - amount;\n            if (newBalance &lt; -this.limit) {\n                return false;\n            }\n            this.balance = newBalance;\n            return true;\n        }\n\n        // ------- PRIVATE METHODS ---------\n\n        private int getCVV() {\n            return this.CVV;\n        }\n\n        private int getBalance() {\n            return this.balance;\n        }\n\n        private void setBalance(final int balance) {\n            this.balance = balance;\n        }\n\n        private int getLimit() {\n            return limit;\n        }\n\n        private void setLimit(final int limit) {\n            this.limit = limit;\n        }\n    }\n}\n</code></pre>\n"}, {'answer_id': 71098085, 'author': 'Jonathan Cole', 'author_id': 2592155, 'author_profile': 'https://Stackoverflow.com/users/2592155', 'pm_score': 0, 'selected': False, 'text': '<p>Static nested classes access PRIVATE class-level static variables of the class they are defined in. That can be huge from an architectural standpoint (i.e. Service Locator pattern employing nested static helper classes in Services), and may help OP see why they exist along with inner classes.</p>\n'}]
['https://Stackoverflow.com/questions/70324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11193/']