-1

I've recently realised you could do this (at least in Java 1.7+).

static interface MyInter {
    int foo = 3; 
}
static {
    System.out.println(MyInter.foo);
}

How exactly is this legal? Does the java compiler just turn int foo into a final static field behind the scene or something?

(If that's the case, then, wow, Java is getting crazier and crazier!)

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
One Two Three
  • 22,327
  • 24
  • 73
  • 114

2 Answers2

5

Yes, fields declared in interfaces are implicitly public, static, and final.

Section 9.3 of the JLS states:

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

The specification allows for interfaces to have fields. All of which are public static final, however these modifiers may be omitted.

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.3

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189