Java Inner Classes and Static Methods or Fields

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

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

However, these answers do not clarify my question. What would be the implications of using static fields and methods for inner classes? I assume both constraints are related. Since static methods will 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 the inner states), this will cause the inner class to behave like static. However, the JVM can restrict access from static methods in inner classes to static methods and data inside the inner class. However, the question arises: why can't we declare static non-final variables inside inner classes?

Is this project or are you having problems?

respectfully

+3


source to share


1 answer


Declaring static variables in a non-static inner class seems to be inconsistent for creating a non-static inner class.
If you declare some variables and methods static, you do so when it makes sense to access them without instantiating the class, if you declare the inner class as a non-static instance type, so the intent is to access it through your instance, not statically. If you declare the inner class static, so you separate it from the outer class, you can declare the variables and methods static.
You asked what would be the consequences if java allows you to declare static methods / fields in non-static inner classes. Well, they probably won't. But it just doesn't make sense, so it's a design choice.



0


source







All Articles