8
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?

slafochmed
  • 115
  • 1
  • 1
  • 4
  • This question is duplicated: see [why-cant-we-have-static-method-in-a-non-static-inner-class](http://stackoverflow.com/questions/975134/why-cant-we-have-static-method-in-a-non-static-inner-class) – wake-0 May 29 '16 at 12:44

4 Answers4

3

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.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
1

Static implies that it can be used without any instance. For instantiating Objects of non static inner class an instance of outer class is needed. Without an object of outer class non static nested inner class can not be instantiated.

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

Inner2 is not static. Inner2 can not be used until its instantiated. Hence any references or methods can only be used once it is instantiated. As Inner2 is not static so existence of D3 only makes sense once we have an object of Inner2 and it being declared as static makes no sense.

For the second question I have another related doubt, so I prefer to add the link to the question I have asked : Why compile time constants are allowed to be made static in non static inner classes?

Hope fully once we have answer to that question, we will have better complete understanding.

Community
  • 1
  • 1
nits.kk
  • 5,204
  • 4
  • 33
  • 55
0

Either move the class

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

outside of the enumerator Or declare it static too

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • If I put the enum in its own file under the same package, it still does not compile, with keeping the same error. And the inner class I want to instantiate but keep the enum value for all instances... – slafochmed May 29 '16 at 12:42
0

As per the java documentation: Inner classes may not declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

Inner classes may not 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