Home > OS >  Something I don't understand about Inner Classes
Something I don't understand about Inner Classes

Time:09-11

Please check the following link, if you want to read the full article https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

It is written there that local classes and inner classes share that they both can't define or declare any static members, also interfaces can't be declared inside blocks, but when I tried the provided code as an example, the code compiled with no errors. I did write my own example, it is something like

public class A { 
    class B { 
        public static String static-field = ...; 
        public static void Method() {...}
    }
}

and this code was also compiled with no errors. I'm a little confused. can static methods and fields be declared inside inner classes and local classes or not?

CodePudding user response:

You are most likely compiling using JDK 16 or higher. The documentation you linked is only for Java 8 and also has been called out at he beginning of the site.

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.

Take a look at Java Language Changes in JDK 16.

In this release, inner classes may declare members that are either explicitly or implicitly static.

CodePudding user response:

This is allowed since Java 16:

While JEP 384 allowed for static local classes and interfaces, it did not relax the restriction on static member classes and interfaces of inner classes. An inner class could declare a static interface inside one of its method bodies, but not as a class member.

As a natural next step, JEP 395 further relaxes nesting restrictions, and permits static classes, methods, fields, etc., to be declared within inner classes.

  • Related