Inner classes can have the static members inside it in java 17?

268 views Asked by At

I was reading the articles regarding the inner classes and out of curiosity I declared the static members within the inner class. Strangely no compile time error was shown and the code just executed fine.

I referred back the oracle documents and could still found the statement : 'because an inner class is associated with an instance, it cannot define any static members itself.'

I am really confused, if there is an enhancement to the inner classes done with the later versions of java where we can now declare the static members within the inner classes as well?

Any light on that will be appreciated.

Here is the code snippet you may try with Java 17:

class Outer{
     class Inner{
          static int i =10;
          public static void method(){
              System.out.println("The static members can be now declared within Inner classes!!!!");
          }
     }
}
2

There are 2 answers

0
MC Emperor On

From the Oracle docs:

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.

And a proposal to relax rules of static members, from openjdk.org:

Resolution: Approved. Fix Version/s: 16

So, yeah, it's allowed for inner classes to have static members, but the Oracle documentation was written to include features of up to Java 8. The rules have changed since Java 16.

0
WJS On

From Java 6 language specification.

An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

To illustrate these rules, consider the example below: (Taken from the Java 6 LS)

class HasStatic{
    static int j = 100;
}
class Outer{
    class Inner extends HasStatic{
        static final int x = 3;         // ok - compile-time constant
        static int y = 4;           // compile-time error, an inner class
    }
    static class NestedButNotInner{
        static int z = 5;           // ok, not an inner class
    }
    interface NeverInner{}              // interfaces are never inner
}

This was relaxed in JEP 395 that finalized the inclusion of record as a standard feature of the language. The statement reads:

This JEP proposes to finalize the feature in JDK 16, with the following refinement:

Relax the longstanding restriction whereby an inner class cannot declare a member that is explicitly or implicitly static. This will become legal and, in particular, will allow an inner class to declare a member that is a record class.