Why can't we have static method in a (non-static) inner class?











up vote
133
down vote

favorite
47












Why can't we have static method in a non-static inner class ?



If I make the inner class static it works. Why ?










share|improve this question




















  • 4




    Because now Java is that old COBOL :)
    – ses
    May 7 '14 at 18:08










  • The bottom line is: because they haven't implemented it yet.
    – intrepidis
    Feb 3 '17 at 1:12






  • 1




    'Non-static inner' is a tautology.
    – user207421
    Jan 22 at 21:02










  • If you don't want to exposure your inner class to others and hope it contain static methods, you can put the modifiers both "private" and "static" on the inner class.
    – Willie Z
    Mar 25 at 22:08










  • An inner class is by definition not static. You can have a static nested/member class, and a non-static nested/member class. The latter is also known as an inner class. (Reference: section 8.1.3 of the JLS states "An inner class is a nested class that is not explicitly or implicitly declared static.")
    – Erwin Bolwidt
    Aug 27 at 0:05















up vote
133
down vote

favorite
47












Why can't we have static method in a non-static inner class ?



If I make the inner class static it works. Why ?










share|improve this question




















  • 4




    Because now Java is that old COBOL :)
    – ses
    May 7 '14 at 18:08










  • The bottom line is: because they haven't implemented it yet.
    – intrepidis
    Feb 3 '17 at 1:12






  • 1




    'Non-static inner' is a tautology.
    – user207421
    Jan 22 at 21:02










  • If you don't want to exposure your inner class to others and hope it contain static methods, you can put the modifiers both "private" and "static" on the inner class.
    – Willie Z
    Mar 25 at 22:08










  • An inner class is by definition not static. You can have a static nested/member class, and a non-static nested/member class. The latter is also known as an inner class. (Reference: section 8.1.3 of the JLS states "An inner class is a nested class that is not explicitly or implicitly declared static.")
    – Erwin Bolwidt
    Aug 27 at 0:05













up vote
133
down vote

favorite
47









up vote
133
down vote

favorite
47






47





Why can't we have static method in a non-static inner class ?



If I make the inner class static it works. Why ?










share|improve this question















Why can't we have static method in a non-static inner class ?



If I make the inner class static it works. Why ?







java class static inner-classes






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 22 '14 at 17:37









Zo72

6,984115188




6,984115188










asked Jun 10 '09 at 11:52









Rahul Garg

4,03082727




4,03082727








  • 4




    Because now Java is that old COBOL :)
    – ses
    May 7 '14 at 18:08










  • The bottom line is: because they haven't implemented it yet.
    – intrepidis
    Feb 3 '17 at 1:12






  • 1




    'Non-static inner' is a tautology.
    – user207421
    Jan 22 at 21:02










  • If you don't want to exposure your inner class to others and hope it contain static methods, you can put the modifiers both "private" and "static" on the inner class.
    – Willie Z
    Mar 25 at 22:08










  • An inner class is by definition not static. You can have a static nested/member class, and a non-static nested/member class. The latter is also known as an inner class. (Reference: section 8.1.3 of the JLS states "An inner class is a nested class that is not explicitly or implicitly declared static.")
    – Erwin Bolwidt
    Aug 27 at 0:05














  • 4




    Because now Java is that old COBOL :)
    – ses
    May 7 '14 at 18:08










  • The bottom line is: because they haven't implemented it yet.
    – intrepidis
    Feb 3 '17 at 1:12






  • 1




    'Non-static inner' is a tautology.
    – user207421
    Jan 22 at 21:02










  • If you don't want to exposure your inner class to others and hope it contain static methods, you can put the modifiers both "private" and "static" on the inner class.
    – Willie Z
    Mar 25 at 22:08










  • An inner class is by definition not static. You can have a static nested/member class, and a non-static nested/member class. The latter is also known as an inner class. (Reference: section 8.1.3 of the JLS states "An inner class is a nested class that is not explicitly or implicitly declared static.")
    – Erwin Bolwidt
    Aug 27 at 0:05








4




4




Because now Java is that old COBOL :)
– ses
May 7 '14 at 18:08




Because now Java is that old COBOL :)
– ses
May 7 '14 at 18:08












The bottom line is: because they haven't implemented it yet.
– intrepidis
Feb 3 '17 at 1:12




The bottom line is: because they haven't implemented it yet.
– intrepidis
Feb 3 '17 at 1:12




1




1




'Non-static inner' is a tautology.
– user207421
Jan 22 at 21:02




'Non-static inner' is a tautology.
– user207421
Jan 22 at 21:02












If you don't want to exposure your inner class to others and hope it contain static methods, you can put the modifiers both "private" and "static" on the inner class.
– Willie Z
Mar 25 at 22:08




If you don't want to exposure your inner class to others and hope it contain static methods, you can put the modifiers both "private" and "static" on the inner class.
– Willie Z
Mar 25 at 22:08












An inner class is by definition not static. You can have a static nested/member class, and a non-static nested/member class. The latter is also known as an inner class. (Reference: section 8.1.3 of the JLS states "An inner class is a nested class that is not explicitly or implicitly declared static.")
– Erwin Bolwidt
Aug 27 at 0:05




An inner class is by definition not static. You can have a static nested/member class, and a non-static nested/member class. The latter is also known as an inner class. (Reference: section 8.1.3 of the JLS states "An inner class is a nested class that is not explicitly or implicitly declared static.")
– Erwin Bolwidt
Aug 27 at 0:05












14 Answers
14






active

oldest

votes

















up vote
101
down vote



accepted










Because an instance of an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class.






share|improve this answer



















  • 5




    I know an inner class is associated with an instance of its outer class and I know that it's kinda useless that we become able to declare static members within an inner class but I am still asking why not an inner class can declare static members?
    – Kareem
    Sep 28 '13 at 18:39








  • 13




    In C++ you can have, so this is a bug in the Java language.
    – Industrial-antidepressant
    Oct 23 '13 at 16:57






  • 38




    The word bug...I do not think that word means what you think it means.
    – Seth Nelson
    Jan 17 '14 at 23:28






  • 21




    A more appropriate phrase would be 'annoying as a mothertrucker'. Don't understand why Java doesn't allow for this. Sometimes, I want an inner class to use properties of the parent class, but keep static methods for better namespacing. Is there something inherently wrong with this? :(
    – Angad
    Aug 5 '15 at 7:27






  • 4




    Exactly. I want to write a utility inner class. Some of its methods would benefit from access to the outer class, so I can't make it static, but some of its methods are just utility functions. Why can't I call A.B.sync(X) or even (from within A) B.sync(x)?
    – Edward Falk
    Nov 11 '15 at 19:00


















up vote
42
down vote













There's not much point to allowing a static method in a non-static inner class; how would you access it? You cannot access (at least initially) a non-static inner class instance without going through an outer class instance. There is no purely static way to create a non-static inner class.



For an outer class Outer, you can access a static method test() like this:



Outer.test();


For a static inner class Inner, you can access its static method innerTest() like this:



Outer.Inner.innerTest();


However, if Inner is not static, there is now no purely static way to reference the method innertest. Non-static inner classes are tied to a specific instance of their outer class. A function is different from a constant, in that a reference to Outer.Inner.CONSTANT is guaranteed to be unambiguous in a way that a function call Outer.Inner.staticFunction(); is not. Let's say you have Inner.staticFunction() that calls getState(), which is defined in Outer. If you try to invoke that static function, you now have an ambiguous reference to the Inner class. That is, on which instance of the inner class do you invoke the static function? It matters. See, there is no truly static way to reference that static method, due to the implicit reference to the outer object.



Paul Bellora is correct that the language designers could have allowed this. They would then have to carefully disallow any access to the implicit reference to the outer class in static methods of the non-static inner class. At this point, what is the value to this being an inner class if you cannot reference the outer class, except statically? And if static access is fine, then why not declare the whole inner class static? If you simply make the inner class itself static, then you have no implicit reference to the outer class, and you no longer have this ambiguity.



If you actually need static methods on a non-static inner class, then you probably need to rethink your design.






share|improve this answer



















  • 5




    -1 I have to disagree with the angle you took here. Certainly we can refer an inner class type, for example Outer.Inner i = new Outer().new Inner(); Also, inner classes are allowed to declare static constants according to JLS §15.28.
    – Paul Bellora
    Feb 7 '13 at 6:13








  • 2




    Yes, inner classes can declare static constants. That has nothing to do with static methods! While you can refer to a static method non-statically, this is discouraged. All code quality tools complain at that kind of reference and for good reason. And you missed my point. I never said there is no way to reference a static inner class. I said there is no STATIC way to reference the static method of an inner class of a non-static outer class. Thus, there is no PROPER way to reference it.
    – Eddie
    Feb 8 '13 at 4:33






  • 19




    "There's not much point to allowing a static method in a non-static inner class; how would you access it?" You would call Outer.Inner.staticMethod() just like you can access Outer.Inner.CONSTANT. "You cannot access ... a non-static inner class instance without going through an outer class instance." Why would you need an instance? You don't need an instance of Outer to call Outer.staticMethod(). I know this is nitpicky but my point is that it doesn't make sense to frame your answer this way. IMHO the language designers could've allowed it if they wished.
    – Paul Bellora
    Feb 8 '13 at 17:13








  • 1




    The difference between Outer.Inner.CONSTANT and Outer.Inner.staticMethod() is that a reference to a constant has no chance of implicitly referencing the instance of Outer in which Inner was instantiated. All references to Outer.staticMethod() share the same exact state. All references to Outer.Inner.CONSTANT share the same exact state. However, references to Outer.Inner.staticMethod() are ambiguous: The "static" state is not truly static, due to the implicit reference to the outer class in each instance of Inner. There is not a truly unambiguous, static way to access it.
    – Eddie
    Feb 11 '13 at 23:55






  • 3




    @Eddie You can't refer to instance fields in a static method, so there is no conflict related to the inability to refer to the implicit instance field Outer.this. I do agree with the Java language designers that there is no reason to allow static methods or non-final static fields in inner classes, because everything in an inner class should be within the context of the enclosing class.
    – Theodore Murdock
    Jul 8 '14 at 19:48


















up vote
18
down vote













I have a theory, which may or may not be correct.



First, you should know some things about how inner classes are implemented in Java. Suppose you've got this class:



class Outer {
private int foo = 0;
class Inner implements Runnable {
public void run(){ foo++; }
}
public Runnable newFooIncrementer(){ return new Inner(); }
}


When you compile it, the generated bytecode will look as if you wrote something like this:



class Outer {
private int foo = 0;
static class Inner implements Runnable {
private final Outer this$0;
public Inner(Outer outer){
this$0 = outer;
}
public void run(){ this$0.foo++; }
}
public Runnable newFooIncrementer(){ return new Inner(this); }
}


Now, if we did allow static methods in non-static inner classes, you might want to do something like this.



class Outer {
private int foo = 0;
class Inner {
public static void incrFoo(){ foo++; }
}
}


... which looks fairly reasonable, as the Inner class seems to have one incarnation per Outer instance. But as we saw above, the non-static inner classes really are just syntactic sugar for static "inner" classes, so the last example would be approximately equivalent to:



class Outer {
private int foo = 0;
static class Inner {
private final Outer this$0;
public Inner(Outer outer){
this$0 = outer;
}
public static void incrFoo(){ this$0.foo++; }
}
}


... which clearly won't work, since this$0 is non-static. This sort of explains why static methods aren't allowed (although you could make the argument that you could allow static methods as long as they didn't reference the enclosing object), and why you can't have non-final static fields (it would be counter-intuitive if instances of non-static inner classes from different objects shared "static state"). It also explains why final fields are allowed (as long as they don't reference the enclosing object).






share|improve this answer

















  • 7




    But that's just a normal "attempt to access non-static variable from a static context" type error - no different from if a top level static method tries to access it's own class's instance variable.
    – Lawrence Dol
    May 10 '11 at 5:29






  • 2




    I like this anwser because it actually explains why it isn't technically possible, even though it could seem possible syntactically.
    – LoPoBo
    Jul 2 '15 at 15:19










  • @gustafc, I think that was an excellent explanation. But as Lawrence points out, it's only a failure because of the reference to foo, which isn't static. But what if I wanted to write public static double sinDeg(double theta) { ... } an an inner math utilities class?
    – Edward Falk
    Nov 11 '15 at 19:09












  • inner class is static , so you cannot access the foo member..
    – howerknea
    Jun 23 '16 at 3:04


















up vote
6
down vote













The only reason is "not a must", so why bother to support it?



Syntactically,there is no reason to prohibit an inner class from having static members. Although an instance of Inner is associated with an instance of Outer, it's still possible to use Outer.Inner.myStatic to refer a static member of Inner if java decides to do so.



If you need to share something among all the instances of Inner, you can just put them into Outer as static members. This is not worse than you use static members in Inner, where Outer can still access any private member of Inner anyway(does not improve encapsulation).



If you need to share something among all the instances of Inner created by one outer object,it makes more sense to put them into Outer class as ordinary members.



I don't agree the opinion that "a static nested class is pretty much just a top level class". I think its better to really regard a static nested class/inner class as a part of the outer class, because they can access outer class's private members. And members of outer class are "members of inner class" as well. So there is no need to support static member in inner class. An ordinary/static member in outer class will suffice.






share|improve this answer























  • Inner classes are not a "must" either. However, as the language does provide inner classes, it should provide a complete and meaningful implementation of them.
    – intrepidis
    Feb 3 '17 at 1:05


















up vote
3
down vote













Short answer: The mental model most programmers have of how scope works is not the model used by javac. Matching the more intuitive model would have required a big change to how javac works.



The main reason that static members in inner classes are desirable is for code cleanliness - a static member used only by an inner class ought to live inside it, rather than having to be placed in the outer class. Consider:



class Outer {
int outID;

class Inner {
static int nextID;
int id = nextID++;

String getID() {
return outID + ":" + id;
}
}
}


Consider what is going on in getID() when I use the unqualified identifier "outID". The scope in which this identifier appears looks something like:



Outer -> Inner -> getID()


Here, again because this is just how javac works, the "Outer" level of the scope includes both static and instance members of Outer. This is confusing because we are usually told to think of the static part of a class as another level of the scope:



Outer static -> Outer instance -> instanceMethod()
----> staticMethod()


In this way of thinking about it, of course staticMethod() can only see static members of Outer. But if that were how javac works, then referencing an instance variable in a static method would result in a "name cannot be resolved" error. What really happens is that the name is found in scope, but then an extra level of check kicks in and figures out that the name was declared in an instance context and is being referenced from a static context.



OK, how does this relate to inner classes? Naively, we think there is no reason inner classes can't have a static scope, because we are picturing the scope working like this:



Outer static -> Outer instance -> Inner instance -> getID()
------ Inner static ------^


In other words, static declarations in the inner class and instance declarations in the outer class are both in scope within the instance context of the inner class, but neither of these is actually nested in the other; both are instead nested in the static scope of Outer.



That's just not how javac works - there is a single level of scope for both static and instance members, and scope always strictly nests. Even inheritance is implemented by copying declarations into the subclass rather than branching and searching the superclass scope.



To support static members of inner classes javac would have to either split static and instance scopes and support branching and rejoining scope hierarchies, or it would have to extend its simple boolean "static context" idea to change to track the type of context at all levels of nested class in the current scope.






share|improve this answer























  • I think a more fundamental difficulty with allowing non-static inner classes to have non-constant static members is that programmers declaring such members might be intending to have them bound to instances of the outer class, or have them be truly static. In cases where a construct--if legal--could sensibly be specified as meaning either of two different things, and where both of those things can be expressed in other unambiguous ways, specifying that construct as being illegal is often better than specifying it as having either meaning.
    – supercat
    Mar 18 '14 at 20:17


















up vote
3
down vote














Why can't we have static method in a non-static inner class ?




Note: A non-static nested class is known as inner class so you do not have non-static inner class as such.



An inner class instance has no existence without a corresponding instance of outer class. An inner class cannot declare static members other than compile time constants. If it were allowed then there would have been ambiguity about meaning of static. In that case there would have been certain confusions:




  1. Does it mean there is only one instance in VM?

  2. Or only one instance per outer object?


That is why the designers probably took the decision of not handling this issue at all.




If I make the inner class static it works. Why ?




Again you cannot make an inner class static rather you can declare a static class as nested. In that case this nested class is actually part of outer class and can have static members without any issue.






share|improve this answer




























    up vote
    3
    down vote













    This topic has garnered attention from many, still I will try to explain in the most simplest of terms.



    Firstly, with reference to http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1, a class or interface is initialized immediately before the first occurence/invocation of any member which is preceeded by the static keyword.




    1. So, if we put up with a static member within an inner class, it will lead to the initialization of the inner class, not necessarily the outer/enclosing class. So, we hamper the class initialization sequence.


    2. Also consider the fact that a non-static inner class is associated with the instance of an enclosing/outer class. So, associating with an instance will mean, that the inner class will exist inside an Outer class instance and will be different amongst instances.



    Simplifying the point, in order to access the static member we need an instance of an Outer class, from which we will again need to create an instance of non-static inner class. Static members are not supposed to be bound to instances and therefore you receive a compilation error.






    share|improve this answer




























      up vote
      2
      down vote













      An inner class is something completely different from a static nested class although both are similar in syntax. Static nested classes are only a means for grouping whereas inner classes have a strong association - and access to all values of - their outer class. You should be sure why you want to use an inner class and then it should come pretty natural which one you have to use. If you need to declare a static method it's probably a static nested class you want anyway.






      share|improve this answer





















      • Benedikt, what do you mean when you say "static nested classes are only a means to grouping" ?
        – Ankur
        Sep 30 '09 at 5:37










      • @Ankur > think "namespace"
        – Gregory Pakosz
        Dec 23 '09 at 16:57


















      up vote
      2
      down vote













      From: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html




      As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.




      Oracle's explanation is superficial and handwavy. Since there's no technical or syntactic reason to preempt static members within an inner class (it's allowed in other languages such as C#) the Java designers' motivation was likely conceptual taste and/or a matter of technical convenience.



      Here's my speculation:



      Unlike top-level classes, inner classes are instance-dependent: an inner-class instance is associated with an instance of every one of its outer classes and has direct access to their members. This is the chief motivation for having them in Java. Expressed another way: an inner class is meant for instantiation in the context of an outer class instance. Without an outer class instance, an inner class ought not be any more usable than the other instance members of the outer class. Let's refer to this as the instance-dependent spirit of inner classes.



      The very nature of static members (which are NOT object-oriented) clashes with the instance-dependent spirit of inner classes (which IS object-oriented) because you can reference/call a static member of an inner class without an outer class instance by using the qualified inner class name.



      Static variables in particular may offend in yet another way: two instances of an inner class that are associated with different instances of the outer class would share static variables. Since variables are a component of state, the two inner class instances would, in effect, share state independently of the outer class instances they're associated with. It’s not that it’s unacceptable that static variables work this way (we accept them in Java as a sensible compromise to OOP purity), but there’s arguably a deeper offense to be had by allowing them in inner classes whose instances are already coupled with outer class instances by design. Forbidding static members within inner classes in favor of the instance-dependent spirit reaps the added bonus of preempting this deeper OOP offense.



      On the other hand, no such offense is entailed by static constants, which do not meaningfully constitute state and so these are allowable. Why not forbid static constants for maximum consistency with the instance-dependent spirit? Perhaps because constants need not take up more memory than necessary (if they're forced to be non-static then they’re copied into every inner class instance which is potentially wasteful). Otherwise I can’t imagine the reason for the exception.



      It may not be rock-solid reasoning but IMO it makes the most sense of Oracle's cursory remark on the matter.






      share|improve this answer






























        up vote
        0
        down vote













        suppose there are two instances of outer class & they both have instantiated inner class.Now if inner class has one static member then it will keep only one copy of that member in heap area.In this case both objects of outer class will refer to this single copy & they can alter it together.This can cause "Dirty read" situation hence to prevent this Java has applied this restriction.Another strong point to support this argument is that java allows final static members here, those whose values can't be changed from either of outer class object.
        Please do let me if i am wrong.






        share|improve this answer

















        • 1




          Not even close to correct.
          – Lawrence Dol
          May 10 '11 at 19:23


















        up vote
        0
        down vote













        First of all why someone want to define the static member in a non-static inner class? answer is, so that the outer class member can use those static member with the inner class name only, Right?



        But for this case we can directly define the member in outer class. which will be associated with all object of inner class, within the outer class instance.



        like below code,



        public class Outer {

        class Inner {

        public static void method() {

        }

        }

        }


        can be written like this



        public class Outer {

        void method() {

        }

        class Inner {


        }

        }


        So in my opinion not to complicate the code java designer is not allowing this functionality or we may see this functionality in future releases with some more features.






        share|improve this answer




























          up vote
          0
          down vote













          Try to treat the class as a normal field, then you will understand.



          //something must be static. Suppose something is an inner class, then it has static keyword which means it's a static class
          Outer.something





          share|improve this answer




























            up vote
            -1
            down vote













            It is useless to have inner class members as static because you won't be able to access them in the first place.



            Think about this, to access a static member you use className.memberName ,, in our case , it should be something like outerclassName.innerclassName.memberName,,, now do you see why innerclass must be static....






            share|improve this answer




























              up vote
              -2
              down vote













              You are allowed static methods on static nested classes. For example



              public class Outer {

              public static class Inner {

              public static void method() {

              }
              }
              }





              share|improve this answer





















                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f975134%2fwhy-cant-we-have-static-method-in-a-non-static-inner-class%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                14 Answers
                14






                active

                oldest

                votes








                14 Answers
                14






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                101
                down vote



                accepted










                Because an instance of an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class.






                share|improve this answer



















                • 5




                  I know an inner class is associated with an instance of its outer class and I know that it's kinda useless that we become able to declare static members within an inner class but I am still asking why not an inner class can declare static members?
                  – Kareem
                  Sep 28 '13 at 18:39








                • 13




                  In C++ you can have, so this is a bug in the Java language.
                  – Industrial-antidepressant
                  Oct 23 '13 at 16:57






                • 38




                  The word bug...I do not think that word means what you think it means.
                  – Seth Nelson
                  Jan 17 '14 at 23:28






                • 21




                  A more appropriate phrase would be 'annoying as a mothertrucker'. Don't understand why Java doesn't allow for this. Sometimes, I want an inner class to use properties of the parent class, but keep static methods for better namespacing. Is there something inherently wrong with this? :(
                  – Angad
                  Aug 5 '15 at 7:27






                • 4




                  Exactly. I want to write a utility inner class. Some of its methods would benefit from access to the outer class, so I can't make it static, but some of its methods are just utility functions. Why can't I call A.B.sync(X) or even (from within A) B.sync(x)?
                  – Edward Falk
                  Nov 11 '15 at 19:00















                up vote
                101
                down vote



                accepted










                Because an instance of an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class.






                share|improve this answer



















                • 5




                  I know an inner class is associated with an instance of its outer class and I know that it's kinda useless that we become able to declare static members within an inner class but I am still asking why not an inner class can declare static members?
                  – Kareem
                  Sep 28 '13 at 18:39








                • 13




                  In C++ you can have, so this is a bug in the Java language.
                  – Industrial-antidepressant
                  Oct 23 '13 at 16:57






                • 38




                  The word bug...I do not think that word means what you think it means.
                  – Seth Nelson
                  Jan 17 '14 at 23:28






                • 21




                  A more appropriate phrase would be 'annoying as a mothertrucker'. Don't understand why Java doesn't allow for this. Sometimes, I want an inner class to use properties of the parent class, but keep static methods for better namespacing. Is there something inherently wrong with this? :(
                  – Angad
                  Aug 5 '15 at 7:27






                • 4




                  Exactly. I want to write a utility inner class. Some of its methods would benefit from access to the outer class, so I can't make it static, but some of its methods are just utility functions. Why can't I call A.B.sync(X) or even (from within A) B.sync(x)?
                  – Edward Falk
                  Nov 11 '15 at 19:00













                up vote
                101
                down vote



                accepted







                up vote
                101
                down vote



                accepted






                Because an instance of an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class.






                share|improve this answer














                Because an instance of an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Sep 25 '15 at 12:16

























                answered Jun 10 '09 at 12:02









                Bill the Lizard

                287k156490786




                287k156490786








                • 5




                  I know an inner class is associated with an instance of its outer class and I know that it's kinda useless that we become able to declare static members within an inner class but I am still asking why not an inner class can declare static members?
                  – Kareem
                  Sep 28 '13 at 18:39








                • 13




                  In C++ you can have, so this is a bug in the Java language.
                  – Industrial-antidepressant
                  Oct 23 '13 at 16:57






                • 38




                  The word bug...I do not think that word means what you think it means.
                  – Seth Nelson
                  Jan 17 '14 at 23:28






                • 21




                  A more appropriate phrase would be 'annoying as a mothertrucker'. Don't understand why Java doesn't allow for this. Sometimes, I want an inner class to use properties of the parent class, but keep static methods for better namespacing. Is there something inherently wrong with this? :(
                  – Angad
                  Aug 5 '15 at 7:27






                • 4




                  Exactly. I want to write a utility inner class. Some of its methods would benefit from access to the outer class, so I can't make it static, but some of its methods are just utility functions. Why can't I call A.B.sync(X) or even (from within A) B.sync(x)?
                  – Edward Falk
                  Nov 11 '15 at 19:00














                • 5




                  I know an inner class is associated with an instance of its outer class and I know that it's kinda useless that we become able to declare static members within an inner class but I am still asking why not an inner class can declare static members?
                  – Kareem
                  Sep 28 '13 at 18:39








                • 13




                  In C++ you can have, so this is a bug in the Java language.
                  – Industrial-antidepressant
                  Oct 23 '13 at 16:57






                • 38




                  The word bug...I do not think that word means what you think it means.
                  – Seth Nelson
                  Jan 17 '14 at 23:28






                • 21




                  A more appropriate phrase would be 'annoying as a mothertrucker'. Don't understand why Java doesn't allow for this. Sometimes, I want an inner class to use properties of the parent class, but keep static methods for better namespacing. Is there something inherently wrong with this? :(
                  – Angad
                  Aug 5 '15 at 7:27






                • 4




                  Exactly. I want to write a utility inner class. Some of its methods would benefit from access to the outer class, so I can't make it static, but some of its methods are just utility functions. Why can't I call A.B.sync(X) or even (from within A) B.sync(x)?
                  – Edward Falk
                  Nov 11 '15 at 19:00








                5




                5




                I know an inner class is associated with an instance of its outer class and I know that it's kinda useless that we become able to declare static members within an inner class but I am still asking why not an inner class can declare static members?
                – Kareem
                Sep 28 '13 at 18:39






                I know an inner class is associated with an instance of its outer class and I know that it's kinda useless that we become able to declare static members within an inner class but I am still asking why not an inner class can declare static members?
                – Kareem
                Sep 28 '13 at 18:39






                13




                13




                In C++ you can have, so this is a bug in the Java language.
                – Industrial-antidepressant
                Oct 23 '13 at 16:57




                In C++ you can have, so this is a bug in the Java language.
                – Industrial-antidepressant
                Oct 23 '13 at 16:57




                38




                38




                The word bug...I do not think that word means what you think it means.
                – Seth Nelson
                Jan 17 '14 at 23:28




                The word bug...I do not think that word means what you think it means.
                – Seth Nelson
                Jan 17 '14 at 23:28




                21




                21




                A more appropriate phrase would be 'annoying as a mothertrucker'. Don't understand why Java doesn't allow for this. Sometimes, I want an inner class to use properties of the parent class, but keep static methods for better namespacing. Is there something inherently wrong with this? :(
                – Angad
                Aug 5 '15 at 7:27




                A more appropriate phrase would be 'annoying as a mothertrucker'. Don't understand why Java doesn't allow for this. Sometimes, I want an inner class to use properties of the parent class, but keep static methods for better namespacing. Is there something inherently wrong with this? :(
                – Angad
                Aug 5 '15 at 7:27




                4




                4




                Exactly. I want to write a utility inner class. Some of its methods would benefit from access to the outer class, so I can't make it static, but some of its methods are just utility functions. Why can't I call A.B.sync(X) or even (from within A) B.sync(x)?
                – Edward Falk
                Nov 11 '15 at 19:00




                Exactly. I want to write a utility inner class. Some of its methods would benefit from access to the outer class, so I can't make it static, but some of its methods are just utility functions. Why can't I call A.B.sync(X) or even (from within A) B.sync(x)?
                – Edward Falk
                Nov 11 '15 at 19:00












                up vote
                42
                down vote













                There's not much point to allowing a static method in a non-static inner class; how would you access it? You cannot access (at least initially) a non-static inner class instance without going through an outer class instance. There is no purely static way to create a non-static inner class.



                For an outer class Outer, you can access a static method test() like this:



                Outer.test();


                For a static inner class Inner, you can access its static method innerTest() like this:



                Outer.Inner.innerTest();


                However, if Inner is not static, there is now no purely static way to reference the method innertest. Non-static inner classes are tied to a specific instance of their outer class. A function is different from a constant, in that a reference to Outer.Inner.CONSTANT is guaranteed to be unambiguous in a way that a function call Outer.Inner.staticFunction(); is not. Let's say you have Inner.staticFunction() that calls getState(), which is defined in Outer. If you try to invoke that static function, you now have an ambiguous reference to the Inner class. That is, on which instance of the inner class do you invoke the static function? It matters. See, there is no truly static way to reference that static method, due to the implicit reference to the outer object.



                Paul Bellora is correct that the language designers could have allowed this. They would then have to carefully disallow any access to the implicit reference to the outer class in static methods of the non-static inner class. At this point, what is the value to this being an inner class if you cannot reference the outer class, except statically? And if static access is fine, then why not declare the whole inner class static? If you simply make the inner class itself static, then you have no implicit reference to the outer class, and you no longer have this ambiguity.



                If you actually need static methods on a non-static inner class, then you probably need to rethink your design.






                share|improve this answer



















                • 5




                  -1 I have to disagree with the angle you took here. Certainly we can refer an inner class type, for example Outer.Inner i = new Outer().new Inner(); Also, inner classes are allowed to declare static constants according to JLS §15.28.
                  – Paul Bellora
                  Feb 7 '13 at 6:13








                • 2




                  Yes, inner classes can declare static constants. That has nothing to do with static methods! While you can refer to a static method non-statically, this is discouraged. All code quality tools complain at that kind of reference and for good reason. And you missed my point. I never said there is no way to reference a static inner class. I said there is no STATIC way to reference the static method of an inner class of a non-static outer class. Thus, there is no PROPER way to reference it.
                  – Eddie
                  Feb 8 '13 at 4:33






                • 19




                  "There's not much point to allowing a static method in a non-static inner class; how would you access it?" You would call Outer.Inner.staticMethod() just like you can access Outer.Inner.CONSTANT. "You cannot access ... a non-static inner class instance without going through an outer class instance." Why would you need an instance? You don't need an instance of Outer to call Outer.staticMethod(). I know this is nitpicky but my point is that it doesn't make sense to frame your answer this way. IMHO the language designers could've allowed it if they wished.
                  – Paul Bellora
                  Feb 8 '13 at 17:13








                • 1




                  The difference between Outer.Inner.CONSTANT and Outer.Inner.staticMethod() is that a reference to a constant has no chance of implicitly referencing the instance of Outer in which Inner was instantiated. All references to Outer.staticMethod() share the same exact state. All references to Outer.Inner.CONSTANT share the same exact state. However, references to Outer.Inner.staticMethod() are ambiguous: The "static" state is not truly static, due to the implicit reference to the outer class in each instance of Inner. There is not a truly unambiguous, static way to access it.
                  – Eddie
                  Feb 11 '13 at 23:55






                • 3




                  @Eddie You can't refer to instance fields in a static method, so there is no conflict related to the inability to refer to the implicit instance field Outer.this. I do agree with the Java language designers that there is no reason to allow static methods or non-final static fields in inner classes, because everything in an inner class should be within the context of the enclosing class.
                  – Theodore Murdock
                  Jul 8 '14 at 19:48















                up vote
                42
                down vote













                There's not much point to allowing a static method in a non-static inner class; how would you access it? You cannot access (at least initially) a non-static inner class instance without going through an outer class instance. There is no purely static way to create a non-static inner class.



                For an outer class Outer, you can access a static method test() like this:



                Outer.test();


                For a static inner class Inner, you can access its static method innerTest() like this:



                Outer.Inner.innerTest();


                However, if Inner is not static, there is now no purely static way to reference the method innertest. Non-static inner classes are tied to a specific instance of their outer class. A function is different from a constant, in that a reference to Outer.Inner.CONSTANT is guaranteed to be unambiguous in a way that a function call Outer.Inner.staticFunction(); is not. Let's say you have Inner.staticFunction() that calls getState(), which is defined in Outer. If you try to invoke that static function, you now have an ambiguous reference to the Inner class. That is, on which instance of the inner class do you invoke the static function? It matters. See, there is no truly static way to reference that static method, due to the implicit reference to the outer object.



                Paul Bellora is correct that the language designers could have allowed this. They would then have to carefully disallow any access to the implicit reference to the outer class in static methods of the non-static inner class. At this point, what is the value to this being an inner class if you cannot reference the outer class, except statically? And if static access is fine, then why not declare the whole inner class static? If you simply make the inner class itself static, then you have no implicit reference to the outer class, and you no longer have this ambiguity.



                If you actually need static methods on a non-static inner class, then you probably need to rethink your design.






                share|improve this answer



















                • 5




                  -1 I have to disagree with the angle you took here. Certainly we can refer an inner class type, for example Outer.Inner i = new Outer().new Inner(); Also, inner classes are allowed to declare static constants according to JLS §15.28.
                  – Paul Bellora
                  Feb 7 '13 at 6:13








                • 2




                  Yes, inner classes can declare static constants. That has nothing to do with static methods! While you can refer to a static method non-statically, this is discouraged. All code quality tools complain at that kind of reference and for good reason. And you missed my point. I never said there is no way to reference a static inner class. I said there is no STATIC way to reference the static method of an inner class of a non-static outer class. Thus, there is no PROPER way to reference it.
                  – Eddie
                  Feb 8 '13 at 4:33






                • 19




                  "There's not much point to allowing a static method in a non-static inner class; how would you access it?" You would call Outer.Inner.staticMethod() just like you can access Outer.Inner.CONSTANT. "You cannot access ... a non-static inner class instance without going through an outer class instance." Why would you need an instance? You don't need an instance of Outer to call Outer.staticMethod(). I know this is nitpicky but my point is that it doesn't make sense to frame your answer this way. IMHO the language designers could've allowed it if they wished.
                  – Paul Bellora
                  Feb 8 '13 at 17:13








                • 1




                  The difference between Outer.Inner.CONSTANT and Outer.Inner.staticMethod() is that a reference to a constant has no chance of implicitly referencing the instance of Outer in which Inner was instantiated. All references to Outer.staticMethod() share the same exact state. All references to Outer.Inner.CONSTANT share the same exact state. However, references to Outer.Inner.staticMethod() are ambiguous: The "static" state is not truly static, due to the implicit reference to the outer class in each instance of Inner. There is not a truly unambiguous, static way to access it.
                  – Eddie
                  Feb 11 '13 at 23:55






                • 3




                  @Eddie You can't refer to instance fields in a static method, so there is no conflict related to the inability to refer to the implicit instance field Outer.this. I do agree with the Java language designers that there is no reason to allow static methods or non-final static fields in inner classes, because everything in an inner class should be within the context of the enclosing class.
                  – Theodore Murdock
                  Jul 8 '14 at 19:48













                up vote
                42
                down vote










                up vote
                42
                down vote









                There's not much point to allowing a static method in a non-static inner class; how would you access it? You cannot access (at least initially) a non-static inner class instance without going through an outer class instance. There is no purely static way to create a non-static inner class.



                For an outer class Outer, you can access a static method test() like this:



                Outer.test();


                For a static inner class Inner, you can access its static method innerTest() like this:



                Outer.Inner.innerTest();


                However, if Inner is not static, there is now no purely static way to reference the method innertest. Non-static inner classes are tied to a specific instance of their outer class. A function is different from a constant, in that a reference to Outer.Inner.CONSTANT is guaranteed to be unambiguous in a way that a function call Outer.Inner.staticFunction(); is not. Let's say you have Inner.staticFunction() that calls getState(), which is defined in Outer. If you try to invoke that static function, you now have an ambiguous reference to the Inner class. That is, on which instance of the inner class do you invoke the static function? It matters. See, there is no truly static way to reference that static method, due to the implicit reference to the outer object.



                Paul Bellora is correct that the language designers could have allowed this. They would then have to carefully disallow any access to the implicit reference to the outer class in static methods of the non-static inner class. At this point, what is the value to this being an inner class if you cannot reference the outer class, except statically? And if static access is fine, then why not declare the whole inner class static? If you simply make the inner class itself static, then you have no implicit reference to the outer class, and you no longer have this ambiguity.



                If you actually need static methods on a non-static inner class, then you probably need to rethink your design.






                share|improve this answer














                There's not much point to allowing a static method in a non-static inner class; how would you access it? You cannot access (at least initially) a non-static inner class instance without going through an outer class instance. There is no purely static way to create a non-static inner class.



                For an outer class Outer, you can access a static method test() like this:



                Outer.test();


                For a static inner class Inner, you can access its static method innerTest() like this:



                Outer.Inner.innerTest();


                However, if Inner is not static, there is now no purely static way to reference the method innertest. Non-static inner classes are tied to a specific instance of their outer class. A function is different from a constant, in that a reference to Outer.Inner.CONSTANT is guaranteed to be unambiguous in a way that a function call Outer.Inner.staticFunction(); is not. Let's say you have Inner.staticFunction() that calls getState(), which is defined in Outer. If you try to invoke that static function, you now have an ambiguous reference to the Inner class. That is, on which instance of the inner class do you invoke the static function? It matters. See, there is no truly static way to reference that static method, due to the implicit reference to the outer object.



                Paul Bellora is correct that the language designers could have allowed this. They would then have to carefully disallow any access to the implicit reference to the outer class in static methods of the non-static inner class. At this point, what is the value to this being an inner class if you cannot reference the outer class, except statically? And if static access is fine, then why not declare the whole inner class static? If you simply make the inner class itself static, then you have no implicit reference to the outer class, and you no longer have this ambiguity.



                If you actually need static methods on a non-static inner class, then you probably need to rethink your design.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Feb 12 '13 at 0:11

























                answered Jun 10 '09 at 13:22









                Eddie

                45k18105135




                45k18105135








                • 5




                  -1 I have to disagree with the angle you took here. Certainly we can refer an inner class type, for example Outer.Inner i = new Outer().new Inner(); Also, inner classes are allowed to declare static constants according to JLS §15.28.
                  – Paul Bellora
                  Feb 7 '13 at 6:13








                • 2




                  Yes, inner classes can declare static constants. That has nothing to do with static methods! While you can refer to a static method non-statically, this is discouraged. All code quality tools complain at that kind of reference and for good reason. And you missed my point. I never said there is no way to reference a static inner class. I said there is no STATIC way to reference the static method of an inner class of a non-static outer class. Thus, there is no PROPER way to reference it.
                  – Eddie
                  Feb 8 '13 at 4:33






                • 19




                  "There's not much point to allowing a static method in a non-static inner class; how would you access it?" You would call Outer.Inner.staticMethod() just like you can access Outer.Inner.CONSTANT. "You cannot access ... a non-static inner class instance without going through an outer class instance." Why would you need an instance? You don't need an instance of Outer to call Outer.staticMethod(). I know this is nitpicky but my point is that it doesn't make sense to frame your answer this way. IMHO the language designers could've allowed it if they wished.
                  – Paul Bellora
                  Feb 8 '13 at 17:13








                • 1




                  The difference between Outer.Inner.CONSTANT and Outer.Inner.staticMethod() is that a reference to a constant has no chance of implicitly referencing the instance of Outer in which Inner was instantiated. All references to Outer.staticMethod() share the same exact state. All references to Outer.Inner.CONSTANT share the same exact state. However, references to Outer.Inner.staticMethod() are ambiguous: The "static" state is not truly static, due to the implicit reference to the outer class in each instance of Inner. There is not a truly unambiguous, static way to access it.
                  – Eddie
                  Feb 11 '13 at 23:55






                • 3




                  @Eddie You can't refer to instance fields in a static method, so there is no conflict related to the inability to refer to the implicit instance field Outer.this. I do agree with the Java language designers that there is no reason to allow static methods or non-final static fields in inner classes, because everything in an inner class should be within the context of the enclosing class.
                  – Theodore Murdock
                  Jul 8 '14 at 19:48














                • 5




                  -1 I have to disagree with the angle you took here. Certainly we can refer an inner class type, for example Outer.Inner i = new Outer().new Inner(); Also, inner classes are allowed to declare static constants according to JLS §15.28.
                  – Paul Bellora
                  Feb 7 '13 at 6:13








                • 2




                  Yes, inner classes can declare static constants. That has nothing to do with static methods! While you can refer to a static method non-statically, this is discouraged. All code quality tools complain at that kind of reference and for good reason. And you missed my point. I never said there is no way to reference a static inner class. I said there is no STATIC way to reference the static method of an inner class of a non-static outer class. Thus, there is no PROPER way to reference it.
                  – Eddie
                  Feb 8 '13 at 4:33






                • 19




                  "There's not much point to allowing a static method in a non-static inner class; how would you access it?" You would call Outer.Inner.staticMethod() just like you can access Outer.Inner.CONSTANT. "You cannot access ... a non-static inner class instance without going through an outer class instance." Why would you need an instance? You don't need an instance of Outer to call Outer.staticMethod(). I know this is nitpicky but my point is that it doesn't make sense to frame your answer this way. IMHO the language designers could've allowed it if they wished.
                  – Paul Bellora
                  Feb 8 '13 at 17:13








                • 1




                  The difference between Outer.Inner.CONSTANT and Outer.Inner.staticMethod() is that a reference to a constant has no chance of implicitly referencing the instance of Outer in which Inner was instantiated. All references to Outer.staticMethod() share the same exact state. All references to Outer.Inner.CONSTANT share the same exact state. However, references to Outer.Inner.staticMethod() are ambiguous: The "static" state is not truly static, due to the implicit reference to the outer class in each instance of Inner. There is not a truly unambiguous, static way to access it.
                  – Eddie
                  Feb 11 '13 at 23:55






                • 3




                  @Eddie You can't refer to instance fields in a static method, so there is no conflict related to the inability to refer to the implicit instance field Outer.this. I do agree with the Java language designers that there is no reason to allow static methods or non-final static fields in inner classes, because everything in an inner class should be within the context of the enclosing class.
                  – Theodore Murdock
                  Jul 8 '14 at 19:48








                5




                5




                -1 I have to disagree with the angle you took here. Certainly we can refer an inner class type, for example Outer.Inner i = new Outer().new Inner(); Also, inner classes are allowed to declare static constants according to JLS §15.28.
                – Paul Bellora
                Feb 7 '13 at 6:13






                -1 I have to disagree with the angle you took here. Certainly we can refer an inner class type, for example Outer.Inner i = new Outer().new Inner(); Also, inner classes are allowed to declare static constants according to JLS §15.28.
                – Paul Bellora
                Feb 7 '13 at 6:13






                2




                2




                Yes, inner classes can declare static constants. That has nothing to do with static methods! While you can refer to a static method non-statically, this is discouraged. All code quality tools complain at that kind of reference and for good reason. And you missed my point. I never said there is no way to reference a static inner class. I said there is no STATIC way to reference the static method of an inner class of a non-static outer class. Thus, there is no PROPER way to reference it.
                – Eddie
                Feb 8 '13 at 4:33




                Yes, inner classes can declare static constants. That has nothing to do with static methods! While you can refer to a static method non-statically, this is discouraged. All code quality tools complain at that kind of reference and for good reason. And you missed my point. I never said there is no way to reference a static inner class. I said there is no STATIC way to reference the static method of an inner class of a non-static outer class. Thus, there is no PROPER way to reference it.
                – Eddie
                Feb 8 '13 at 4:33




                19




                19




                "There's not much point to allowing a static method in a non-static inner class; how would you access it?" You would call Outer.Inner.staticMethod() just like you can access Outer.Inner.CONSTANT. "You cannot access ... a non-static inner class instance without going through an outer class instance." Why would you need an instance? You don't need an instance of Outer to call Outer.staticMethod(). I know this is nitpicky but my point is that it doesn't make sense to frame your answer this way. IMHO the language designers could've allowed it if they wished.
                – Paul Bellora
                Feb 8 '13 at 17:13






                "There's not much point to allowing a static method in a non-static inner class; how would you access it?" You would call Outer.Inner.staticMethod() just like you can access Outer.Inner.CONSTANT. "You cannot access ... a non-static inner class instance without going through an outer class instance." Why would you need an instance? You don't need an instance of Outer to call Outer.staticMethod(). I know this is nitpicky but my point is that it doesn't make sense to frame your answer this way. IMHO the language designers could've allowed it if they wished.
                – Paul Bellora
                Feb 8 '13 at 17:13






                1




                1




                The difference between Outer.Inner.CONSTANT and Outer.Inner.staticMethod() is that a reference to a constant has no chance of implicitly referencing the instance of Outer in which Inner was instantiated. All references to Outer.staticMethod() share the same exact state. All references to Outer.Inner.CONSTANT share the same exact state. However, references to Outer.Inner.staticMethod() are ambiguous: The "static" state is not truly static, due to the implicit reference to the outer class in each instance of Inner. There is not a truly unambiguous, static way to access it.
                – Eddie
                Feb 11 '13 at 23:55




                The difference between Outer.Inner.CONSTANT and Outer.Inner.staticMethod() is that a reference to a constant has no chance of implicitly referencing the instance of Outer in which Inner was instantiated. All references to Outer.staticMethod() share the same exact state. All references to Outer.Inner.CONSTANT share the same exact state. However, references to Outer.Inner.staticMethod() are ambiguous: The "static" state is not truly static, due to the implicit reference to the outer class in each instance of Inner. There is not a truly unambiguous, static way to access it.
                – Eddie
                Feb 11 '13 at 23:55




                3




                3




                @Eddie You can't refer to instance fields in a static method, so there is no conflict related to the inability to refer to the implicit instance field Outer.this. I do agree with the Java language designers that there is no reason to allow static methods or non-final static fields in inner classes, because everything in an inner class should be within the context of the enclosing class.
                – Theodore Murdock
                Jul 8 '14 at 19:48




                @Eddie You can't refer to instance fields in a static method, so there is no conflict related to the inability to refer to the implicit instance field Outer.this. I do agree with the Java language designers that there is no reason to allow static methods or non-final static fields in inner classes, because everything in an inner class should be within the context of the enclosing class.
                – Theodore Murdock
                Jul 8 '14 at 19:48










                up vote
                18
                down vote













                I have a theory, which may or may not be correct.



                First, you should know some things about how inner classes are implemented in Java. Suppose you've got this class:



                class Outer {
                private int foo = 0;
                class Inner implements Runnable {
                public void run(){ foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(); }
                }


                When you compile it, the generated bytecode will look as if you wrote something like this:



                class Outer {
                private int foo = 0;
                static class Inner implements Runnable {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public void run(){ this$0.foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(this); }
                }


                Now, if we did allow static methods in non-static inner classes, you might want to do something like this.



                class Outer {
                private int foo = 0;
                class Inner {
                public static void incrFoo(){ foo++; }
                }
                }


                ... which looks fairly reasonable, as the Inner class seems to have one incarnation per Outer instance. But as we saw above, the non-static inner classes really are just syntactic sugar for static "inner" classes, so the last example would be approximately equivalent to:



                class Outer {
                private int foo = 0;
                static class Inner {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public static void incrFoo(){ this$0.foo++; }
                }
                }


                ... which clearly won't work, since this$0 is non-static. This sort of explains why static methods aren't allowed (although you could make the argument that you could allow static methods as long as they didn't reference the enclosing object), and why you can't have non-final static fields (it would be counter-intuitive if instances of non-static inner classes from different objects shared "static state"). It also explains why final fields are allowed (as long as they don't reference the enclosing object).






                share|improve this answer

















                • 7




                  But that's just a normal "attempt to access non-static variable from a static context" type error - no different from if a top level static method tries to access it's own class's instance variable.
                  – Lawrence Dol
                  May 10 '11 at 5:29






                • 2




                  I like this anwser because it actually explains why it isn't technically possible, even though it could seem possible syntactically.
                  – LoPoBo
                  Jul 2 '15 at 15:19










                • @gustafc, I think that was an excellent explanation. But as Lawrence points out, it's only a failure because of the reference to foo, which isn't static. But what if I wanted to write public static double sinDeg(double theta) { ... } an an inner math utilities class?
                  – Edward Falk
                  Nov 11 '15 at 19:09












                • inner class is static , so you cannot access the foo member..
                  – howerknea
                  Jun 23 '16 at 3:04















                up vote
                18
                down vote













                I have a theory, which may or may not be correct.



                First, you should know some things about how inner classes are implemented in Java. Suppose you've got this class:



                class Outer {
                private int foo = 0;
                class Inner implements Runnable {
                public void run(){ foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(); }
                }


                When you compile it, the generated bytecode will look as if you wrote something like this:



                class Outer {
                private int foo = 0;
                static class Inner implements Runnable {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public void run(){ this$0.foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(this); }
                }


                Now, if we did allow static methods in non-static inner classes, you might want to do something like this.



                class Outer {
                private int foo = 0;
                class Inner {
                public static void incrFoo(){ foo++; }
                }
                }


                ... which looks fairly reasonable, as the Inner class seems to have one incarnation per Outer instance. But as we saw above, the non-static inner classes really are just syntactic sugar for static "inner" classes, so the last example would be approximately equivalent to:



                class Outer {
                private int foo = 0;
                static class Inner {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public static void incrFoo(){ this$0.foo++; }
                }
                }


                ... which clearly won't work, since this$0 is non-static. This sort of explains why static methods aren't allowed (although you could make the argument that you could allow static methods as long as they didn't reference the enclosing object), and why you can't have non-final static fields (it would be counter-intuitive if instances of non-static inner classes from different objects shared "static state"). It also explains why final fields are allowed (as long as they don't reference the enclosing object).






                share|improve this answer

















                • 7




                  But that's just a normal "attempt to access non-static variable from a static context" type error - no different from if a top level static method tries to access it's own class's instance variable.
                  – Lawrence Dol
                  May 10 '11 at 5:29






                • 2




                  I like this anwser because it actually explains why it isn't technically possible, even though it could seem possible syntactically.
                  – LoPoBo
                  Jul 2 '15 at 15:19










                • @gustafc, I think that was an excellent explanation. But as Lawrence points out, it's only a failure because of the reference to foo, which isn't static. But what if I wanted to write public static double sinDeg(double theta) { ... } an an inner math utilities class?
                  – Edward Falk
                  Nov 11 '15 at 19:09












                • inner class is static , so you cannot access the foo member..
                  – howerknea
                  Jun 23 '16 at 3:04













                up vote
                18
                down vote










                up vote
                18
                down vote









                I have a theory, which may or may not be correct.



                First, you should know some things about how inner classes are implemented in Java. Suppose you've got this class:



                class Outer {
                private int foo = 0;
                class Inner implements Runnable {
                public void run(){ foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(); }
                }


                When you compile it, the generated bytecode will look as if you wrote something like this:



                class Outer {
                private int foo = 0;
                static class Inner implements Runnable {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public void run(){ this$0.foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(this); }
                }


                Now, if we did allow static methods in non-static inner classes, you might want to do something like this.



                class Outer {
                private int foo = 0;
                class Inner {
                public static void incrFoo(){ foo++; }
                }
                }


                ... which looks fairly reasonable, as the Inner class seems to have one incarnation per Outer instance. But as we saw above, the non-static inner classes really are just syntactic sugar for static "inner" classes, so the last example would be approximately equivalent to:



                class Outer {
                private int foo = 0;
                static class Inner {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public static void incrFoo(){ this$0.foo++; }
                }
                }


                ... which clearly won't work, since this$0 is non-static. This sort of explains why static methods aren't allowed (although you could make the argument that you could allow static methods as long as they didn't reference the enclosing object), and why you can't have non-final static fields (it would be counter-intuitive if instances of non-static inner classes from different objects shared "static state"). It also explains why final fields are allowed (as long as they don't reference the enclosing object).






                share|improve this answer












                I have a theory, which may or may not be correct.



                First, you should know some things about how inner classes are implemented in Java. Suppose you've got this class:



                class Outer {
                private int foo = 0;
                class Inner implements Runnable {
                public void run(){ foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(); }
                }


                When you compile it, the generated bytecode will look as if you wrote something like this:



                class Outer {
                private int foo = 0;
                static class Inner implements Runnable {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public void run(){ this$0.foo++; }
                }
                public Runnable newFooIncrementer(){ return new Inner(this); }
                }


                Now, if we did allow static methods in non-static inner classes, you might want to do something like this.



                class Outer {
                private int foo = 0;
                class Inner {
                public static void incrFoo(){ foo++; }
                }
                }


                ... which looks fairly reasonable, as the Inner class seems to have one incarnation per Outer instance. But as we saw above, the non-static inner classes really are just syntactic sugar for static "inner" classes, so the last example would be approximately equivalent to:



                class Outer {
                private int foo = 0;
                static class Inner {
                private final Outer this$0;
                public Inner(Outer outer){
                this$0 = outer;
                }
                public static void incrFoo(){ this$0.foo++; }
                }
                }


                ... which clearly won't work, since this$0 is non-static. This sort of explains why static methods aren't allowed (although you could make the argument that you could allow static methods as long as they didn't reference the enclosing object), and why you can't have non-final static fields (it would be counter-intuitive if instances of non-static inner classes from different objects shared "static state"). It also explains why final fields are allowed (as long as they don't reference the enclosing object).







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jun 10 '09 at 12:31









                gustafc

                23k75486




                23k75486








                • 7




                  But that's just a normal "attempt to access non-static variable from a static context" type error - no different from if a top level static method tries to access it's own class's instance variable.
                  – Lawrence Dol
                  May 10 '11 at 5:29






                • 2




                  I like this anwser because it actually explains why it isn't technically possible, even though it could seem possible syntactically.
                  – LoPoBo
                  Jul 2 '15 at 15:19










                • @gustafc, I think that was an excellent explanation. But as Lawrence points out, it's only a failure because of the reference to foo, which isn't static. But what if I wanted to write public static double sinDeg(double theta) { ... } an an inner math utilities class?
                  – Edward Falk
                  Nov 11 '15 at 19:09












                • inner class is static , so you cannot access the foo member..
                  – howerknea
                  Jun 23 '16 at 3:04














                • 7




                  But that's just a normal "attempt to access non-static variable from a static context" type error - no different from if a top level static method tries to access it's own class's instance variable.
                  – Lawrence Dol
                  May 10 '11 at 5:29






                • 2




                  I like this anwser because it actually explains why it isn't technically possible, even though it could seem possible syntactically.
                  – LoPoBo
                  Jul 2 '15 at 15:19










                • @gustafc, I think that was an excellent explanation. But as Lawrence points out, it's only a failure because of the reference to foo, which isn't static. But what if I wanted to write public static double sinDeg(double theta) { ... } an an inner math utilities class?
                  – Edward Falk
                  Nov 11 '15 at 19:09












                • inner class is static , so you cannot access the foo member..
                  – howerknea
                  Jun 23 '16 at 3:04








                7




                7




                But that's just a normal "attempt to access non-static variable from a static context" type error - no different from if a top level static method tries to access it's own class's instance variable.
                – Lawrence Dol
                May 10 '11 at 5:29




                But that's just a normal "attempt to access non-static variable from a static context" type error - no different from if a top level static method tries to access it's own class's instance variable.
                – Lawrence Dol
                May 10 '11 at 5:29




                2




                2




                I like this anwser because it actually explains why it isn't technically possible, even though it could seem possible syntactically.
                – LoPoBo
                Jul 2 '15 at 15:19




                I like this anwser because it actually explains why it isn't technically possible, even though it could seem possible syntactically.
                – LoPoBo
                Jul 2 '15 at 15:19












                @gustafc, I think that was an excellent explanation. But as Lawrence points out, it's only a failure because of the reference to foo, which isn't static. But what if I wanted to write public static double sinDeg(double theta) { ... } an an inner math utilities class?
                – Edward Falk
                Nov 11 '15 at 19:09






                @gustafc, I think that was an excellent explanation. But as Lawrence points out, it's only a failure because of the reference to foo, which isn't static. But what if I wanted to write public static double sinDeg(double theta) { ... } an an inner math utilities class?
                – Edward Falk
                Nov 11 '15 at 19:09














                inner class is static , so you cannot access the foo member..
                – howerknea
                Jun 23 '16 at 3:04




                inner class is static , so you cannot access the foo member..
                – howerknea
                Jun 23 '16 at 3:04










                up vote
                6
                down vote













                The only reason is "not a must", so why bother to support it?



                Syntactically,there is no reason to prohibit an inner class from having static members. Although an instance of Inner is associated with an instance of Outer, it's still possible to use Outer.Inner.myStatic to refer a static member of Inner if java decides to do so.



                If you need to share something among all the instances of Inner, you can just put them into Outer as static members. This is not worse than you use static members in Inner, where Outer can still access any private member of Inner anyway(does not improve encapsulation).



                If you need to share something among all the instances of Inner created by one outer object,it makes more sense to put them into Outer class as ordinary members.



                I don't agree the opinion that "a static nested class is pretty much just a top level class". I think its better to really regard a static nested class/inner class as a part of the outer class, because they can access outer class's private members. And members of outer class are "members of inner class" as well. So there is no need to support static member in inner class. An ordinary/static member in outer class will suffice.






                share|improve this answer























                • Inner classes are not a "must" either. However, as the language does provide inner classes, it should provide a complete and meaningful implementation of them.
                  – intrepidis
                  Feb 3 '17 at 1:05















                up vote
                6
                down vote













                The only reason is "not a must", so why bother to support it?



                Syntactically,there is no reason to prohibit an inner class from having static members. Although an instance of Inner is associated with an instance of Outer, it's still possible to use Outer.Inner.myStatic to refer a static member of Inner if java decides to do so.



                If you need to share something among all the instances of Inner, you can just put them into Outer as static members. This is not worse than you use static members in Inner, where Outer can still access any private member of Inner anyway(does not improve encapsulation).



                If you need to share something among all the instances of Inner created by one outer object,it makes more sense to put them into Outer class as ordinary members.



                I don't agree the opinion that "a static nested class is pretty much just a top level class". I think its better to really regard a static nested class/inner class as a part of the outer class, because they can access outer class's private members. And members of outer class are "members of inner class" as well. So there is no need to support static member in inner class. An ordinary/static member in outer class will suffice.






                share|improve this answer























                • Inner classes are not a "must" either. However, as the language does provide inner classes, it should provide a complete and meaningful implementation of them.
                  – intrepidis
                  Feb 3 '17 at 1:05













                up vote
                6
                down vote










                up vote
                6
                down vote









                The only reason is "not a must", so why bother to support it?



                Syntactically,there is no reason to prohibit an inner class from having static members. Although an instance of Inner is associated with an instance of Outer, it's still possible to use Outer.Inner.myStatic to refer a static member of Inner if java decides to do so.



                If you need to share something among all the instances of Inner, you can just put them into Outer as static members. This is not worse than you use static members in Inner, where Outer can still access any private member of Inner anyway(does not improve encapsulation).



                If you need to share something among all the instances of Inner created by one outer object,it makes more sense to put them into Outer class as ordinary members.



                I don't agree the opinion that "a static nested class is pretty much just a top level class". I think its better to really regard a static nested class/inner class as a part of the outer class, because they can access outer class's private members. And members of outer class are "members of inner class" as well. So there is no need to support static member in inner class. An ordinary/static member in outer class will suffice.






                share|improve this answer














                The only reason is "not a must", so why bother to support it?



                Syntactically,there is no reason to prohibit an inner class from having static members. Although an instance of Inner is associated with an instance of Outer, it's still possible to use Outer.Inner.myStatic to refer a static member of Inner if java decides to do so.



                If you need to share something among all the instances of Inner, you can just put them into Outer as static members. This is not worse than you use static members in Inner, where Outer can still access any private member of Inner anyway(does not improve encapsulation).



                If you need to share something among all the instances of Inner created by one outer object,it makes more sense to put them into Outer class as ordinary members.



                I don't agree the opinion that "a static nested class is pretty much just a top level class". I think its better to really regard a static nested class/inner class as a part of the outer class, because they can access outer class's private members. And members of outer class are "members of inner class" as well. So there is no need to support static member in inner class. An ordinary/static member in outer class will suffice.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 8 '12 at 5:19

























                answered May 8 '12 at 5:09









                Don Li

                5072716




                5072716












                • Inner classes are not a "must" either. However, as the language does provide inner classes, it should provide a complete and meaningful implementation of them.
                  – intrepidis
                  Feb 3 '17 at 1:05


















                • Inner classes are not a "must" either. However, as the language does provide inner classes, it should provide a complete and meaningful implementation of them.
                  – intrepidis
                  Feb 3 '17 at 1:05
















                Inner classes are not a "must" either. However, as the language does provide inner classes, it should provide a complete and meaningful implementation of them.
                – intrepidis
                Feb 3 '17 at 1:05




                Inner classes are not a "must" either. However, as the language does provide inner classes, it should provide a complete and meaningful implementation of them.
                – intrepidis
                Feb 3 '17 at 1:05










                up vote
                3
                down vote













                Short answer: The mental model most programmers have of how scope works is not the model used by javac. Matching the more intuitive model would have required a big change to how javac works.



                The main reason that static members in inner classes are desirable is for code cleanliness - a static member used only by an inner class ought to live inside it, rather than having to be placed in the outer class. Consider:



                class Outer {
                int outID;

                class Inner {
                static int nextID;
                int id = nextID++;

                String getID() {
                return outID + ":" + id;
                }
                }
                }


                Consider what is going on in getID() when I use the unqualified identifier "outID". The scope in which this identifier appears looks something like:



                Outer -> Inner -> getID()


                Here, again because this is just how javac works, the "Outer" level of the scope includes both static and instance members of Outer. This is confusing because we are usually told to think of the static part of a class as another level of the scope:



                Outer static -> Outer instance -> instanceMethod()
                ----> staticMethod()


                In this way of thinking about it, of course staticMethod() can only see static members of Outer. But if that were how javac works, then referencing an instance variable in a static method would result in a "name cannot be resolved" error. What really happens is that the name is found in scope, but then an extra level of check kicks in and figures out that the name was declared in an instance context and is being referenced from a static context.



                OK, how does this relate to inner classes? Naively, we think there is no reason inner classes can't have a static scope, because we are picturing the scope working like this:



                Outer static -> Outer instance -> Inner instance -> getID()
                ------ Inner static ------^


                In other words, static declarations in the inner class and instance declarations in the outer class are both in scope within the instance context of the inner class, but neither of these is actually nested in the other; both are instead nested in the static scope of Outer.



                That's just not how javac works - there is a single level of scope for both static and instance members, and scope always strictly nests. Even inheritance is implemented by copying declarations into the subclass rather than branching and searching the superclass scope.



                To support static members of inner classes javac would have to either split static and instance scopes and support branching and rejoining scope hierarchies, or it would have to extend its simple boolean "static context" idea to change to track the type of context at all levels of nested class in the current scope.






                share|improve this answer























                • I think a more fundamental difficulty with allowing non-static inner classes to have non-constant static members is that programmers declaring such members might be intending to have them bound to instances of the outer class, or have them be truly static. In cases where a construct--if legal--could sensibly be specified as meaning either of two different things, and where both of those things can be expressed in other unambiguous ways, specifying that construct as being illegal is often better than specifying it as having either meaning.
                  – supercat
                  Mar 18 '14 at 20:17















                up vote
                3
                down vote













                Short answer: The mental model most programmers have of how scope works is not the model used by javac. Matching the more intuitive model would have required a big change to how javac works.



                The main reason that static members in inner classes are desirable is for code cleanliness - a static member used only by an inner class ought to live inside it, rather than having to be placed in the outer class. Consider:



                class Outer {
                int outID;

                class Inner {
                static int nextID;
                int id = nextID++;

                String getID() {
                return outID + ":" + id;
                }
                }
                }


                Consider what is going on in getID() when I use the unqualified identifier "outID". The scope in which this identifier appears looks something like:



                Outer -> Inner -> getID()


                Here, again because this is just how javac works, the "Outer" level of the scope includes both static and instance members of Outer. This is confusing because we are usually told to think of the static part of a class as another level of the scope:



                Outer static -> Outer instance -> instanceMethod()
                ----> staticMethod()


                In this way of thinking about it, of course staticMethod() can only see static members of Outer. But if that were how javac works, then referencing an instance variable in a static method would result in a "name cannot be resolved" error. What really happens is that the name is found in scope, but then an extra level of check kicks in and figures out that the name was declared in an instance context and is being referenced from a static context.



                OK, how does this relate to inner classes? Naively, we think there is no reason inner classes can't have a static scope, because we are picturing the scope working like this:



                Outer static -> Outer instance -> Inner instance -> getID()
                ------ Inner static ------^


                In other words, static declarations in the inner class and instance declarations in the outer class are both in scope within the instance context of the inner class, but neither of these is actually nested in the other; both are instead nested in the static scope of Outer.



                That's just not how javac works - there is a single level of scope for both static and instance members, and scope always strictly nests. Even inheritance is implemented by copying declarations into the subclass rather than branching and searching the superclass scope.



                To support static members of inner classes javac would have to either split static and instance scopes and support branching and rejoining scope hierarchies, or it would have to extend its simple boolean "static context" idea to change to track the type of context at all levels of nested class in the current scope.






                share|improve this answer























                • I think a more fundamental difficulty with allowing non-static inner classes to have non-constant static members is that programmers declaring such members might be intending to have them bound to instances of the outer class, or have them be truly static. In cases where a construct--if legal--could sensibly be specified as meaning either of two different things, and where both of those things can be expressed in other unambiguous ways, specifying that construct as being illegal is often better than specifying it as having either meaning.
                  – supercat
                  Mar 18 '14 at 20:17













                up vote
                3
                down vote










                up vote
                3
                down vote









                Short answer: The mental model most programmers have of how scope works is not the model used by javac. Matching the more intuitive model would have required a big change to how javac works.



                The main reason that static members in inner classes are desirable is for code cleanliness - a static member used only by an inner class ought to live inside it, rather than having to be placed in the outer class. Consider:



                class Outer {
                int outID;

                class Inner {
                static int nextID;
                int id = nextID++;

                String getID() {
                return outID + ":" + id;
                }
                }
                }


                Consider what is going on in getID() when I use the unqualified identifier "outID". The scope in which this identifier appears looks something like:



                Outer -> Inner -> getID()


                Here, again because this is just how javac works, the "Outer" level of the scope includes both static and instance members of Outer. This is confusing because we are usually told to think of the static part of a class as another level of the scope:



                Outer static -> Outer instance -> instanceMethod()
                ----> staticMethod()


                In this way of thinking about it, of course staticMethod() can only see static members of Outer. But if that were how javac works, then referencing an instance variable in a static method would result in a "name cannot be resolved" error. What really happens is that the name is found in scope, but then an extra level of check kicks in and figures out that the name was declared in an instance context and is being referenced from a static context.



                OK, how does this relate to inner classes? Naively, we think there is no reason inner classes can't have a static scope, because we are picturing the scope working like this:



                Outer static -> Outer instance -> Inner instance -> getID()
                ------ Inner static ------^


                In other words, static declarations in the inner class and instance declarations in the outer class are both in scope within the instance context of the inner class, but neither of these is actually nested in the other; both are instead nested in the static scope of Outer.



                That's just not how javac works - there is a single level of scope for both static and instance members, and scope always strictly nests. Even inheritance is implemented by copying declarations into the subclass rather than branching and searching the superclass scope.



                To support static members of inner classes javac would have to either split static and instance scopes and support branching and rejoining scope hierarchies, or it would have to extend its simple boolean "static context" idea to change to track the type of context at all levels of nested class in the current scope.






                share|improve this answer














                Short answer: The mental model most programmers have of how scope works is not the model used by javac. Matching the more intuitive model would have required a big change to how javac works.



                The main reason that static members in inner classes are desirable is for code cleanliness - a static member used only by an inner class ought to live inside it, rather than having to be placed in the outer class. Consider:



                class Outer {
                int outID;

                class Inner {
                static int nextID;
                int id = nextID++;

                String getID() {
                return outID + ":" + id;
                }
                }
                }


                Consider what is going on in getID() when I use the unqualified identifier "outID". The scope in which this identifier appears looks something like:



                Outer -> Inner -> getID()


                Here, again because this is just how javac works, the "Outer" level of the scope includes both static and instance members of Outer. This is confusing because we are usually told to think of the static part of a class as another level of the scope:



                Outer static -> Outer instance -> instanceMethod()
                ----> staticMethod()


                In this way of thinking about it, of course staticMethod() can only see static members of Outer. But if that were how javac works, then referencing an instance variable in a static method would result in a "name cannot be resolved" error. What really happens is that the name is found in scope, but then an extra level of check kicks in and figures out that the name was declared in an instance context and is being referenced from a static context.



                OK, how does this relate to inner classes? Naively, we think there is no reason inner classes can't have a static scope, because we are picturing the scope working like this:



                Outer static -> Outer instance -> Inner instance -> getID()
                ------ Inner static ------^


                In other words, static declarations in the inner class and instance declarations in the outer class are both in scope within the instance context of the inner class, but neither of these is actually nested in the other; both are instead nested in the static scope of Outer.



                That's just not how javac works - there is a single level of scope for both static and instance members, and scope always strictly nests. Even inheritance is implemented by copying declarations into the subclass rather than branching and searching the superclass scope.



                To support static members of inner classes javac would have to either split static and instance scopes and support branching and rejoining scope hierarchies, or it would have to extend its simple boolean "static context" idea to change to track the type of context at all levels of nested class in the current scope.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 8 '12 at 20:15

























                answered Jan 4 '12 at 22:27









                Russell Zahniser

                14.4k2628




                14.4k2628












                • I think a more fundamental difficulty with allowing non-static inner classes to have non-constant static members is that programmers declaring such members might be intending to have them bound to instances of the outer class, or have them be truly static. In cases where a construct--if legal--could sensibly be specified as meaning either of two different things, and where both of those things can be expressed in other unambiguous ways, specifying that construct as being illegal is often better than specifying it as having either meaning.
                  – supercat
                  Mar 18 '14 at 20:17


















                • I think a more fundamental difficulty with allowing non-static inner classes to have non-constant static members is that programmers declaring such members might be intending to have them bound to instances of the outer class, or have them be truly static. In cases where a construct--if legal--could sensibly be specified as meaning either of two different things, and where both of those things can be expressed in other unambiguous ways, specifying that construct as being illegal is often better than specifying it as having either meaning.
                  – supercat
                  Mar 18 '14 at 20:17
















                I think a more fundamental difficulty with allowing non-static inner classes to have non-constant static members is that programmers declaring such members might be intending to have them bound to instances of the outer class, or have them be truly static. In cases where a construct--if legal--could sensibly be specified as meaning either of two different things, and where both of those things can be expressed in other unambiguous ways, specifying that construct as being illegal is often better than specifying it as having either meaning.
                – supercat
                Mar 18 '14 at 20:17




                I think a more fundamental difficulty with allowing non-static inner classes to have non-constant static members is that programmers declaring such members might be intending to have them bound to instances of the outer class, or have them be truly static. In cases where a construct--if legal--could sensibly be specified as meaning either of two different things, and where both of those things can be expressed in other unambiguous ways, specifying that construct as being illegal is often better than specifying it as having either meaning.
                – supercat
                Mar 18 '14 at 20:17










                up vote
                3
                down vote














                Why can't we have static method in a non-static inner class ?




                Note: A non-static nested class is known as inner class so you do not have non-static inner class as such.



                An inner class instance has no existence without a corresponding instance of outer class. An inner class cannot declare static members other than compile time constants. If it were allowed then there would have been ambiguity about meaning of static. In that case there would have been certain confusions:




                1. Does it mean there is only one instance in VM?

                2. Or only one instance per outer object?


                That is why the designers probably took the decision of not handling this issue at all.




                If I make the inner class static it works. Why ?




                Again you cannot make an inner class static rather you can declare a static class as nested. In that case this nested class is actually part of outer class and can have static members without any issue.






                share|improve this answer

























                  up vote
                  3
                  down vote














                  Why can't we have static method in a non-static inner class ?




                  Note: A non-static nested class is known as inner class so you do not have non-static inner class as such.



                  An inner class instance has no existence without a corresponding instance of outer class. An inner class cannot declare static members other than compile time constants. If it were allowed then there would have been ambiguity about meaning of static. In that case there would have been certain confusions:




                  1. Does it mean there is only one instance in VM?

                  2. Or only one instance per outer object?


                  That is why the designers probably took the decision of not handling this issue at all.




                  If I make the inner class static it works. Why ?




                  Again you cannot make an inner class static rather you can declare a static class as nested. In that case this nested class is actually part of outer class and can have static members without any issue.






                  share|improve this answer























                    up vote
                    3
                    down vote










                    up vote
                    3
                    down vote










                    Why can't we have static method in a non-static inner class ?




                    Note: A non-static nested class is known as inner class so you do not have non-static inner class as such.



                    An inner class instance has no existence without a corresponding instance of outer class. An inner class cannot declare static members other than compile time constants. If it were allowed then there would have been ambiguity about meaning of static. In that case there would have been certain confusions:




                    1. Does it mean there is only one instance in VM?

                    2. Or only one instance per outer object?


                    That is why the designers probably took the decision of not handling this issue at all.




                    If I make the inner class static it works. Why ?




                    Again you cannot make an inner class static rather you can declare a static class as nested. In that case this nested class is actually part of outer class and can have static members without any issue.






                    share|improve this answer













                    Why can't we have static method in a non-static inner class ?




                    Note: A non-static nested class is known as inner class so you do not have non-static inner class as such.



                    An inner class instance has no existence without a corresponding instance of outer class. An inner class cannot declare static members other than compile time constants. If it were allowed then there would have been ambiguity about meaning of static. In that case there would have been certain confusions:




                    1. Does it mean there is only one instance in VM?

                    2. Or only one instance per outer object?


                    That is why the designers probably took the decision of not handling this issue at all.




                    If I make the inner class static it works. Why ?




                    Again you cannot make an inner class static rather you can declare a static class as nested. In that case this nested class is actually part of outer class and can have static members without any issue.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Sep 25 '15 at 4:17









                    i_am_zero

                    11k25253




                    11k25253






















                        up vote
                        3
                        down vote













                        This topic has garnered attention from many, still I will try to explain in the most simplest of terms.



                        Firstly, with reference to http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1, a class or interface is initialized immediately before the first occurence/invocation of any member which is preceeded by the static keyword.




                        1. So, if we put up with a static member within an inner class, it will lead to the initialization of the inner class, not necessarily the outer/enclosing class. So, we hamper the class initialization sequence.


                        2. Also consider the fact that a non-static inner class is associated with the instance of an enclosing/outer class. So, associating with an instance will mean, that the inner class will exist inside an Outer class instance and will be different amongst instances.



                        Simplifying the point, in order to access the static member we need an instance of an Outer class, from which we will again need to create an instance of non-static inner class. Static members are not supposed to be bound to instances and therefore you receive a compilation error.






                        share|improve this answer

























                          up vote
                          3
                          down vote













                          This topic has garnered attention from many, still I will try to explain in the most simplest of terms.



                          Firstly, with reference to http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1, a class or interface is initialized immediately before the first occurence/invocation of any member which is preceeded by the static keyword.




                          1. So, if we put up with a static member within an inner class, it will lead to the initialization of the inner class, not necessarily the outer/enclosing class. So, we hamper the class initialization sequence.


                          2. Also consider the fact that a non-static inner class is associated with the instance of an enclosing/outer class. So, associating with an instance will mean, that the inner class will exist inside an Outer class instance and will be different amongst instances.



                          Simplifying the point, in order to access the static member we need an instance of an Outer class, from which we will again need to create an instance of non-static inner class. Static members are not supposed to be bound to instances and therefore you receive a compilation error.






                          share|improve this answer























                            up vote
                            3
                            down vote










                            up vote
                            3
                            down vote









                            This topic has garnered attention from many, still I will try to explain in the most simplest of terms.



                            Firstly, with reference to http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1, a class or interface is initialized immediately before the first occurence/invocation of any member which is preceeded by the static keyword.




                            1. So, if we put up with a static member within an inner class, it will lead to the initialization of the inner class, not necessarily the outer/enclosing class. So, we hamper the class initialization sequence.


                            2. Also consider the fact that a non-static inner class is associated with the instance of an enclosing/outer class. So, associating with an instance will mean, that the inner class will exist inside an Outer class instance and will be different amongst instances.



                            Simplifying the point, in order to access the static member we need an instance of an Outer class, from which we will again need to create an instance of non-static inner class. Static members are not supposed to be bound to instances and therefore you receive a compilation error.






                            share|improve this answer












                            This topic has garnered attention from many, still I will try to explain in the most simplest of terms.



                            Firstly, with reference to http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1, a class or interface is initialized immediately before the first occurence/invocation of any member which is preceeded by the static keyword.




                            1. So, if we put up with a static member within an inner class, it will lead to the initialization of the inner class, not necessarily the outer/enclosing class. So, we hamper the class initialization sequence.


                            2. Also consider the fact that a non-static inner class is associated with the instance of an enclosing/outer class. So, associating with an instance will mean, that the inner class will exist inside an Outer class instance and will be different amongst instances.



                            Simplifying the point, in order to access the static member we need an instance of an Outer class, from which we will again need to create an instance of non-static inner class. Static members are not supposed to be bound to instances and therefore you receive a compilation error.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 24 '17 at 13:07









                            Doomed93

                            14116




                            14116






















                                up vote
                                2
                                down vote













                                An inner class is something completely different from a static nested class although both are similar in syntax. Static nested classes are only a means for grouping whereas inner classes have a strong association - and access to all values of - their outer class. You should be sure why you want to use an inner class and then it should come pretty natural which one you have to use. If you need to declare a static method it's probably a static nested class you want anyway.






                                share|improve this answer





















                                • Benedikt, what do you mean when you say "static nested classes are only a means to grouping" ?
                                  – Ankur
                                  Sep 30 '09 at 5:37










                                • @Ankur > think "namespace"
                                  – Gregory Pakosz
                                  Dec 23 '09 at 16:57















                                up vote
                                2
                                down vote













                                An inner class is something completely different from a static nested class although both are similar in syntax. Static nested classes are only a means for grouping whereas inner classes have a strong association - and access to all values of - their outer class. You should be sure why you want to use an inner class and then it should come pretty natural which one you have to use. If you need to declare a static method it's probably a static nested class you want anyway.






                                share|improve this answer





















                                • Benedikt, what do you mean when you say "static nested classes are only a means to grouping" ?
                                  – Ankur
                                  Sep 30 '09 at 5:37










                                • @Ankur > think "namespace"
                                  – Gregory Pakosz
                                  Dec 23 '09 at 16:57













                                up vote
                                2
                                down vote










                                up vote
                                2
                                down vote









                                An inner class is something completely different from a static nested class although both are similar in syntax. Static nested classes are only a means for grouping whereas inner classes have a strong association - and access to all values of - their outer class. You should be sure why you want to use an inner class and then it should come pretty natural which one you have to use. If you need to declare a static method it's probably a static nested class you want anyway.






                                share|improve this answer












                                An inner class is something completely different from a static nested class although both are similar in syntax. Static nested classes are only a means for grouping whereas inner classes have a strong association - and access to all values of - their outer class. You should be sure why you want to use an inner class and then it should come pretty natural which one you have to use. If you need to declare a static method it's probably a static nested class you want anyway.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jun 10 '09 at 12:10









                                B.E.

                                3,89242639




                                3,89242639












                                • Benedikt, what do you mean when you say "static nested classes are only a means to grouping" ?
                                  – Ankur
                                  Sep 30 '09 at 5:37










                                • @Ankur > think "namespace"
                                  – Gregory Pakosz
                                  Dec 23 '09 at 16:57


















                                • Benedikt, what do you mean when you say "static nested classes are only a means to grouping" ?
                                  – Ankur
                                  Sep 30 '09 at 5:37










                                • @Ankur > think "namespace"
                                  – Gregory Pakosz
                                  Dec 23 '09 at 16:57
















                                Benedikt, what do you mean when you say "static nested classes are only a means to grouping" ?
                                – Ankur
                                Sep 30 '09 at 5:37




                                Benedikt, what do you mean when you say "static nested classes are only a means to grouping" ?
                                – Ankur
                                Sep 30 '09 at 5:37












                                @Ankur > think "namespace"
                                – Gregory Pakosz
                                Dec 23 '09 at 16:57




                                @Ankur > think "namespace"
                                – Gregory Pakosz
                                Dec 23 '09 at 16:57










                                up vote
                                2
                                down vote













                                From: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html




                                As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.




                                Oracle's explanation is superficial and handwavy. Since there's no technical or syntactic reason to preempt static members within an inner class (it's allowed in other languages such as C#) the Java designers' motivation was likely conceptual taste and/or a matter of technical convenience.



                                Here's my speculation:



                                Unlike top-level classes, inner classes are instance-dependent: an inner-class instance is associated with an instance of every one of its outer classes and has direct access to their members. This is the chief motivation for having them in Java. Expressed another way: an inner class is meant for instantiation in the context of an outer class instance. Without an outer class instance, an inner class ought not be any more usable than the other instance members of the outer class. Let's refer to this as the instance-dependent spirit of inner classes.



                                The very nature of static members (which are NOT object-oriented) clashes with the instance-dependent spirit of inner classes (which IS object-oriented) because you can reference/call a static member of an inner class without an outer class instance by using the qualified inner class name.



                                Static variables in particular may offend in yet another way: two instances of an inner class that are associated with different instances of the outer class would share static variables. Since variables are a component of state, the two inner class instances would, in effect, share state independently of the outer class instances they're associated with. It’s not that it’s unacceptable that static variables work this way (we accept them in Java as a sensible compromise to OOP purity), but there’s arguably a deeper offense to be had by allowing them in inner classes whose instances are already coupled with outer class instances by design. Forbidding static members within inner classes in favor of the instance-dependent spirit reaps the added bonus of preempting this deeper OOP offense.



                                On the other hand, no such offense is entailed by static constants, which do not meaningfully constitute state and so these are allowable. Why not forbid static constants for maximum consistency with the instance-dependent spirit? Perhaps because constants need not take up more memory than necessary (if they're forced to be non-static then they’re copied into every inner class instance which is potentially wasteful). Otherwise I can’t imagine the reason for the exception.



                                It may not be rock-solid reasoning but IMO it makes the most sense of Oracle's cursory remark on the matter.






                                share|improve this answer



























                                  up vote
                                  2
                                  down vote













                                  From: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html




                                  As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.




                                  Oracle's explanation is superficial and handwavy. Since there's no technical or syntactic reason to preempt static members within an inner class (it's allowed in other languages such as C#) the Java designers' motivation was likely conceptual taste and/or a matter of technical convenience.



                                  Here's my speculation:



                                  Unlike top-level classes, inner classes are instance-dependent: an inner-class instance is associated with an instance of every one of its outer classes and has direct access to their members. This is the chief motivation for having them in Java. Expressed another way: an inner class is meant for instantiation in the context of an outer class instance. Without an outer class instance, an inner class ought not be any more usable than the other instance members of the outer class. Let's refer to this as the instance-dependent spirit of inner classes.



                                  The very nature of static members (which are NOT object-oriented) clashes with the instance-dependent spirit of inner classes (which IS object-oriented) because you can reference/call a static member of an inner class without an outer class instance by using the qualified inner class name.



                                  Static variables in particular may offend in yet another way: two instances of an inner class that are associated with different instances of the outer class would share static variables. Since variables are a component of state, the two inner class instances would, in effect, share state independently of the outer class instances they're associated with. It’s not that it’s unacceptable that static variables work this way (we accept them in Java as a sensible compromise to OOP purity), but there’s arguably a deeper offense to be had by allowing them in inner classes whose instances are already coupled with outer class instances by design. Forbidding static members within inner classes in favor of the instance-dependent spirit reaps the added bonus of preempting this deeper OOP offense.



                                  On the other hand, no such offense is entailed by static constants, which do not meaningfully constitute state and so these are allowable. Why not forbid static constants for maximum consistency with the instance-dependent spirit? Perhaps because constants need not take up more memory than necessary (if they're forced to be non-static then they’re copied into every inner class instance which is potentially wasteful). Otherwise I can’t imagine the reason for the exception.



                                  It may not be rock-solid reasoning but IMO it makes the most sense of Oracle's cursory remark on the matter.






                                  share|improve this answer

























                                    up vote
                                    2
                                    down vote










                                    up vote
                                    2
                                    down vote









                                    From: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html




                                    As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.




                                    Oracle's explanation is superficial and handwavy. Since there's no technical or syntactic reason to preempt static members within an inner class (it's allowed in other languages such as C#) the Java designers' motivation was likely conceptual taste and/or a matter of technical convenience.



                                    Here's my speculation:



                                    Unlike top-level classes, inner classes are instance-dependent: an inner-class instance is associated with an instance of every one of its outer classes and has direct access to their members. This is the chief motivation for having them in Java. Expressed another way: an inner class is meant for instantiation in the context of an outer class instance. Without an outer class instance, an inner class ought not be any more usable than the other instance members of the outer class. Let's refer to this as the instance-dependent spirit of inner classes.



                                    The very nature of static members (which are NOT object-oriented) clashes with the instance-dependent spirit of inner classes (which IS object-oriented) because you can reference/call a static member of an inner class without an outer class instance by using the qualified inner class name.



                                    Static variables in particular may offend in yet another way: two instances of an inner class that are associated with different instances of the outer class would share static variables. Since variables are a component of state, the two inner class instances would, in effect, share state independently of the outer class instances they're associated with. It’s not that it’s unacceptable that static variables work this way (we accept them in Java as a sensible compromise to OOP purity), but there’s arguably a deeper offense to be had by allowing them in inner classes whose instances are already coupled with outer class instances by design. Forbidding static members within inner classes in favor of the instance-dependent spirit reaps the added bonus of preempting this deeper OOP offense.



                                    On the other hand, no such offense is entailed by static constants, which do not meaningfully constitute state and so these are allowable. Why not forbid static constants for maximum consistency with the instance-dependent spirit? Perhaps because constants need not take up more memory than necessary (if they're forced to be non-static then they’re copied into every inner class instance which is potentially wasteful). Otherwise I can’t imagine the reason for the exception.



                                    It may not be rock-solid reasoning but IMO it makes the most sense of Oracle's cursory remark on the matter.






                                    share|improve this answer














                                    From: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html




                                    As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.




                                    Oracle's explanation is superficial and handwavy. Since there's no technical or syntactic reason to preempt static members within an inner class (it's allowed in other languages such as C#) the Java designers' motivation was likely conceptual taste and/or a matter of technical convenience.



                                    Here's my speculation:



                                    Unlike top-level classes, inner classes are instance-dependent: an inner-class instance is associated with an instance of every one of its outer classes and has direct access to their members. This is the chief motivation for having them in Java. Expressed another way: an inner class is meant for instantiation in the context of an outer class instance. Without an outer class instance, an inner class ought not be any more usable than the other instance members of the outer class. Let's refer to this as the instance-dependent spirit of inner classes.



                                    The very nature of static members (which are NOT object-oriented) clashes with the instance-dependent spirit of inner classes (which IS object-oriented) because you can reference/call a static member of an inner class without an outer class instance by using the qualified inner class name.



                                    Static variables in particular may offend in yet another way: two instances of an inner class that are associated with different instances of the outer class would share static variables. Since variables are a component of state, the two inner class instances would, in effect, share state independently of the outer class instances they're associated with. It’s not that it’s unacceptable that static variables work this way (we accept them in Java as a sensible compromise to OOP purity), but there’s arguably a deeper offense to be had by allowing them in inner classes whose instances are already coupled with outer class instances by design. Forbidding static members within inner classes in favor of the instance-dependent spirit reaps the added bonus of preempting this deeper OOP offense.



                                    On the other hand, no such offense is entailed by static constants, which do not meaningfully constitute state and so these are allowable. Why not forbid static constants for maximum consistency with the instance-dependent spirit? Perhaps because constants need not take up more memory than necessary (if they're forced to be non-static then they’re copied into every inner class instance which is potentially wasteful). Otherwise I can’t imagine the reason for the exception.



                                    It may not be rock-solid reasoning but IMO it makes the most sense of Oracle's cursory remark on the matter.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 10 at 23:08

























                                    answered Oct 22 at 12:18









                                    Benjamin Curtis Drake

                                    212




                                    212






















                                        up vote
                                        0
                                        down vote













                                        suppose there are two instances of outer class & they both have instantiated inner class.Now if inner class has one static member then it will keep only one copy of that member in heap area.In this case both objects of outer class will refer to this single copy & they can alter it together.This can cause "Dirty read" situation hence to prevent this Java has applied this restriction.Another strong point to support this argument is that java allows final static members here, those whose values can't be changed from either of outer class object.
                                        Please do let me if i am wrong.






                                        share|improve this answer

















                                        • 1




                                          Not even close to correct.
                                          – Lawrence Dol
                                          May 10 '11 at 19:23















                                        up vote
                                        0
                                        down vote













                                        suppose there are two instances of outer class & they both have instantiated inner class.Now if inner class has one static member then it will keep only one copy of that member in heap area.In this case both objects of outer class will refer to this single copy & they can alter it together.This can cause "Dirty read" situation hence to prevent this Java has applied this restriction.Another strong point to support this argument is that java allows final static members here, those whose values can't be changed from either of outer class object.
                                        Please do let me if i am wrong.






                                        share|improve this answer

















                                        • 1




                                          Not even close to correct.
                                          – Lawrence Dol
                                          May 10 '11 at 19:23













                                        up vote
                                        0
                                        down vote










                                        up vote
                                        0
                                        down vote









                                        suppose there are two instances of outer class & they both have instantiated inner class.Now if inner class has one static member then it will keep only one copy of that member in heap area.In this case both objects of outer class will refer to this single copy & they can alter it together.This can cause "Dirty read" situation hence to prevent this Java has applied this restriction.Another strong point to support this argument is that java allows final static members here, those whose values can't be changed from either of outer class object.
                                        Please do let me if i am wrong.






                                        share|improve this answer












                                        suppose there are two instances of outer class & they both have instantiated inner class.Now if inner class has one static member then it will keep only one copy of that member in heap area.In this case both objects of outer class will refer to this single copy & they can alter it together.This can cause "Dirty read" situation hence to prevent this Java has applied this restriction.Another strong point to support this argument is that java allows final static members here, those whose values can't be changed from either of outer class object.
                                        Please do let me if i am wrong.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Mar 3 '10 at 15:58









                                        Malay

                                        251




                                        251








                                        • 1




                                          Not even close to correct.
                                          – Lawrence Dol
                                          May 10 '11 at 19:23














                                        • 1




                                          Not even close to correct.
                                          – Lawrence Dol
                                          May 10 '11 at 19:23








                                        1




                                        1




                                        Not even close to correct.
                                        – Lawrence Dol
                                        May 10 '11 at 19:23




                                        Not even close to correct.
                                        – Lawrence Dol
                                        May 10 '11 at 19:23










                                        up vote
                                        0
                                        down vote













                                        First of all why someone want to define the static member in a non-static inner class? answer is, so that the outer class member can use those static member with the inner class name only, Right?



                                        But for this case we can directly define the member in outer class. which will be associated with all object of inner class, within the outer class instance.



                                        like below code,



                                        public class Outer {

                                        class Inner {

                                        public static void method() {

                                        }

                                        }

                                        }


                                        can be written like this



                                        public class Outer {

                                        void method() {

                                        }

                                        class Inner {


                                        }

                                        }


                                        So in my opinion not to complicate the code java designer is not allowing this functionality or we may see this functionality in future releases with some more features.






                                        share|improve this answer

























                                          up vote
                                          0
                                          down vote













                                          First of all why someone want to define the static member in a non-static inner class? answer is, so that the outer class member can use those static member with the inner class name only, Right?



                                          But for this case we can directly define the member in outer class. which will be associated with all object of inner class, within the outer class instance.



                                          like below code,



                                          public class Outer {

                                          class Inner {

                                          public static void method() {

                                          }

                                          }

                                          }


                                          can be written like this



                                          public class Outer {

                                          void method() {

                                          }

                                          class Inner {


                                          }

                                          }


                                          So in my opinion not to complicate the code java designer is not allowing this functionality or we may see this functionality in future releases with some more features.






                                          share|improve this answer























                                            up vote
                                            0
                                            down vote










                                            up vote
                                            0
                                            down vote









                                            First of all why someone want to define the static member in a non-static inner class? answer is, so that the outer class member can use those static member with the inner class name only, Right?



                                            But for this case we can directly define the member in outer class. which will be associated with all object of inner class, within the outer class instance.



                                            like below code,



                                            public class Outer {

                                            class Inner {

                                            public static void method() {

                                            }

                                            }

                                            }


                                            can be written like this



                                            public class Outer {

                                            void method() {

                                            }

                                            class Inner {


                                            }

                                            }


                                            So in my opinion not to complicate the code java designer is not allowing this functionality or we may see this functionality in future releases with some more features.






                                            share|improve this answer












                                            First of all why someone want to define the static member in a non-static inner class? answer is, so that the outer class member can use those static member with the inner class name only, Right?



                                            But for this case we can directly define the member in outer class. which will be associated with all object of inner class, within the outer class instance.



                                            like below code,



                                            public class Outer {

                                            class Inner {

                                            public static void method() {

                                            }

                                            }

                                            }


                                            can be written like this



                                            public class Outer {

                                            void method() {

                                            }

                                            class Inner {


                                            }

                                            }


                                            So in my opinion not to complicate the code java designer is not allowing this functionality or we may see this functionality in future releases with some more features.







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Aug 9 '16 at 7:06









                                            Vishnu Saini

                                            11




                                            11






















                                                up vote
                                                0
                                                down vote













                                                Try to treat the class as a normal field, then you will understand.



                                                //something must be static. Suppose something is an inner class, then it has static keyword which means it's a static class
                                                Outer.something





                                                share|improve this answer

























                                                  up vote
                                                  0
                                                  down vote













                                                  Try to treat the class as a normal field, then you will understand.



                                                  //something must be static. Suppose something is an inner class, then it has static keyword which means it's a static class
                                                  Outer.something





                                                  share|improve this answer























                                                    up vote
                                                    0
                                                    down vote










                                                    up vote
                                                    0
                                                    down vote









                                                    Try to treat the class as a normal field, then you will understand.



                                                    //something must be static. Suppose something is an inner class, then it has static keyword which means it's a static class
                                                    Outer.something





                                                    share|improve this answer












                                                    Try to treat the class as a normal field, then you will understand.



                                                    //something must be static. Suppose something is an inner class, then it has static keyword which means it's a static class
                                                    Outer.something






                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Dec 22 '16 at 2:06









                                                    user1888955

                                                    1891114




                                                    1891114






















                                                        up vote
                                                        -1
                                                        down vote













                                                        It is useless to have inner class members as static because you won't be able to access them in the first place.



                                                        Think about this, to access a static member you use className.memberName ,, in our case , it should be something like outerclassName.innerclassName.memberName,,, now do you see why innerclass must be static....






                                                        share|improve this answer

























                                                          up vote
                                                          -1
                                                          down vote













                                                          It is useless to have inner class members as static because you won't be able to access them in the first place.



                                                          Think about this, to access a static member you use className.memberName ,, in our case , it should be something like outerclassName.innerclassName.memberName,,, now do you see why innerclass must be static....






                                                          share|improve this answer























                                                            up vote
                                                            -1
                                                            down vote










                                                            up vote
                                                            -1
                                                            down vote









                                                            It is useless to have inner class members as static because you won't be able to access them in the first place.



                                                            Think about this, to access a static member you use className.memberName ,, in our case , it should be something like outerclassName.innerclassName.memberName,,, now do you see why innerclass must be static....






                                                            share|improve this answer












                                                            It is useless to have inner class members as static because you won't be able to access them in the first place.



                                                            Think about this, to access a static member you use className.memberName ,, in our case , it should be something like outerclassName.innerclassName.memberName,,, now do you see why innerclass must be static....







                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered May 18 '15 at 16:03









                                                            Creative_Cimmons

                                                            1391111




                                                            1391111






















                                                                up vote
                                                                -2
                                                                down vote













                                                                You are allowed static methods on static nested classes. For example



                                                                public class Outer {

                                                                public static class Inner {

                                                                public static void method() {

                                                                }
                                                                }
                                                                }





                                                                share|improve this answer

























                                                                  up vote
                                                                  -2
                                                                  down vote













                                                                  You are allowed static methods on static nested classes. For example



                                                                  public class Outer {

                                                                  public static class Inner {

                                                                  public static void method() {

                                                                  }
                                                                  }
                                                                  }





                                                                  share|improve this answer























                                                                    up vote
                                                                    -2
                                                                    down vote










                                                                    up vote
                                                                    -2
                                                                    down vote









                                                                    You are allowed static methods on static nested classes. For example



                                                                    public class Outer {

                                                                    public static class Inner {

                                                                    public static void method() {

                                                                    }
                                                                    }
                                                                    }





                                                                    share|improve this answer












                                                                    You are allowed static methods on static nested classes. For example



                                                                    public class Outer {

                                                                    public static class Inner {

                                                                    public static void method() {

                                                                    }
                                                                    }
                                                                    }






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Jun 10 '09 at 12:14









                                                                    mR_fr0g

                                                                    6,30222947




                                                                    6,30222947






























                                                                         

                                                                        draft saved


                                                                        draft discarded



















































                                                                         


                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function () {
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f975134%2fwhy-cant-we-have-static-method-in-a-non-static-inner-class%23new-answer', 'question_page');
                                                                        }
                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        Popular posts from this blog

                                                                        Florida Star v. B. J. F.

                                                                        Error while running script in elastic search , gateway timeout

                                                                        Adding quotations to stringified JSON object values