4
votes

Why can't inner classes have static (non-final) fields and methods?

This question has been posted before but the posted answers were: it's a design decision or because inner classes happen in the context of the outer class and cannot declare static methods.

Yet these answers do not clarify my question. What would be the consequences of allowing static fields and methods on inner classes? My guess is that both restrictions are connected. Since static methods would require access to other static methods and non-final static variables of the inner class or even from the outer class (to be able to change internal states), this would lead a inner class to behave like a static one. The JVM could limit access from static methods in inner classes to static methods and data inside the inner class, though. Yet this raises the question: why can't we declare static non-final variables inside inner classes?

Is this design or there are problems?

Kind regards

2
The fundamental issue is that it doesn't make sense. An inner class is inherently not static; it is attached to an instance of the outer class. Making methods static on the inner class is just nonsensical.Louis Wasserman
You can declare static members inside inner class. The class just has to be static inner class.Balkrishna Rawool
@BalkrishnaRawool OP is asking about inner classes (non-static nested classes).Pshemo
@Pshemo: Ok. Then it is quite obvious that they can't have static members. Because then they have to have instance of the outer class. Thanks Pshemo.Balkrishna Rawool
@LouisWasserman. So it's a problem of applicability, not a problem of potential bugs? Because local classes can't access static fields in the enclosing method because of the closure thing. I thought this would be something similar. I thought this would lead to incongruences. That's my confusion.BrunoMCBraga

2 Answers

0
votes

Declaring static variables in non-static inner class seems contradictory to intend of creating inner non-static class.
If you declaring some variables and methods static you do it when it make sense to access them without creating instance of class, if you declaring inner class non-static its instance type, so intent is to access it via its instance not staticly. If you declare inner class static, therefore separate it from outer class, you can declare variables and methods static.
You asked what would be consequences if java allowed you to declare static methods/fields in inner non-static classes. Well probably there would be none. But it just doesn't make sense, therefore it's a design choice.

0
votes

To answer why... ->
Inner class object is strongly associated with Outer class object that means without existing Outer class object there is no chance of existing Inner class Object, so defining any static variable/method inside Inner class would not fulfill this requirement

In case of static nested class -> Inner class object is NOT strongly associated with Outer class object