A field cannot be declared static in a non-stationary internal type unless initialized with a constant expression

public class Test { public enum Directions { NORTH, WEST, SOUTH, EAST } static final Directions D1 = Directions.NORTH; static class Inner { static final Directions D2 = Directions.NORTH; } class Inner2 { static final Directions D3 = Directions.NORTH; } } 

I get an IDE error, which is in the header, referring to the D3 variable. Can someone explain this to me? Why can't I declare a static variable in an inner class that is not static, and why is the enum value not a constant?

+5
source share
4 answers

JLS §8.1.3 Enclosing inner classes and instances

Inner classes cannot declare static members unless they are constant variables ( §4.12.4 ), or a compile-time error occurs.


Why is the Enum entry not considered a constant variable?

A variable of primitive type or String type, which is final and initialized by the expression of the compile-time constant (§15.28), is called a constant variable.

+3
source

Static implies that it can be used without any instance. To create instances of objects of a non-stationary inner class, an instance of the outer class is required. Without an object of an outer class, a non-stationary nested inner class cannot be created.

 class Inner2 { static final Directions D3 = Directions.NORTH; } 

Inner2 is not static. Inner2 cannot be used until it is created. Therefore, any references or methods can be used only after its creation. Since Inner2 is not static, the existence of D3 only makes sense after we have an Inner2 object and it is declared as static, it makes no sense.

In the second question, I have another doubt, so I prefer to add a link to the question I asked: Why is it allowed to compile time constants static in non-stationary inner classes?

I hope that when we have the answer to this question, we will have a better understanding.

+1
source

Move class

 class Inner2 { static final Directions D3 = Directions.NORTH; } 

outside the counter Or declare it too static

0
source

According to java documentation : Inner classes cannot declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

Inner classes cannot declare static members unless they are constant variables (§4.12.4), or a compile-time error occurs.

enter image description here

enter image description here

0
source

All Articles