0

I know that nested class has not had static member,

class OuterClass {
     class InnerClass {
      private static int x = 0; // this is error
     }

}

But when we declared it with final

 class OuterClass {
     class InnerClass {
      private static final int x = 0; // ok
     }
}

is it related with the final keyword, because variable can't be changed anymore? Or is there another reason for this?

2 Answers 2

1

This behavior is mandated by the Java Language Specification:

8.1.3. Inner Classes and Enclosing Instances

An inner class is a nested class that is not explicitly or implicitly declared static.

An inner class may be a non-static member class (§8.5), a local class (§14.3), or an anonymous class (§15.9.5). A member class of an interface is implicitly static (§9.5) so is never considered to be an inner class.

It is a compile-time error if an inner class declares a static initializer (§8.7).

It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable (§4.12.4).

An inner class may inherit static members that are not constant variables even though it cannot declare them.

A nested class that is not an inner class may declare static members freely, in accordance with the usual rules of the Java programming language.

Example 8.1.3-1. Inner Class Declarations and Static Members

class HasStatic {
     static int j = 100;
}
class Outer {
    class Inner extends HasStatic {
         static final int x = 3;  // OK: constant variable
         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
}

Note that this changed with Java 16:

All of the rules that apply to nested classes apply to inner classes. In particular, an inner class may declare and inherit static members (§8.2), and declare static initializers (§8.7), even though the inner class itself is not static.

Sign up to request clarification or add additional context in comments.

Comments

0

Because private static final int x = 0; is compile time constant. According java doc,

Inner classes may not declare static members, unless they are compile-time constant fields

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.