Home >Java >javaTutorial >Why Can\'t You Define a Static Method in a Non-Static Inner Class in Java Prior to Version 16?
In pre-Java 16 versions, attempting to define a static method within a non-static inner class results in a compiler error. For instance, the following code snippet will fail:
<code class="java">public class Foo { class Bar { static void method() {} // Compiler error } }</code>
Non-static inner classes are tied to instances of their enclosing class. Every instance of the inner class has a hidden reference to its enclosing class instance. This means that static methods within the inner class would have to maintain a reference to the enclosing class, which violates the принцип изоляции интерфейса.
To define static methods within an inner class, you must declare the inner class as static. A static inner class does not have an implicit reference to the instance of its enclosing class. As a result, it can define static methods:
<code class="java">public class Foo { static class Bar { // now static static void method() {} } }</code>
The above is the detailed content of Why Can\'t You Define a Static Method in a Non-Static Inner Class in Java Prior to Version 16?. For more information, please follow other related articles on the PHP Chinese website!