Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

field cannot be declared static in a non-static inner type unless initialized with a constant expression

Tags:

java

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 am getting the IDE-Error which is in the title, referring to the variable D3. Can someone explain that to me? Why can I not declare a static variable in an inner class that is not static and why is the enum value not a constant?

like image 989
slafochmed Avatar asked May 29 '16 12:05

slafochmed


1 Answers

JLS §8.1.3 Inner Classes and Enclosing Instances

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


Why is an Enum entry not considered a constant variable?

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

like image 191
Yassin Hajaj Avatar answered Sep 30 '22 13:09

Yassin Hajaj