7

the code is :

interface I {
    int i = 0;
    void display();
}

class A implements I {
    I i1;

    public static void main(String[] args) {
        A a = new A();
        a.display();
    }

    public void display() {
        System.out.println(i1); //1
        System.out.println(i1.i); //2
    }
}

The output of the code is

null
0

But when the address of the i is null, then in the 2nd i1.i how does it return a value ? How can a null reference be used to point to a variable ?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
jht
  • 605
  • 1
  • 6
  • 16

1 Answers1

20

Fields declared in interfaces are implicitly static.

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.

This

i1.i

is a static field access expression. It relies on the type of i1, not its value. It is exactly equivalent to

I.i // where I is the name of your interface
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 5
    And this is why it isn't a good idea to access static fields through an instance, even though Java allows you to do so. – biziclop Jan 14 '15 at 17:25
  • "Fields declared in interfaces are implicitly static" and final. – dragon66 Jan 14 '15 at 17:26
  • I believe Eclipse even issues a warning when you do that, it's a bad practice in general (though sometimes it's desirable) – MightyPork Jan 14 '15 at 17:27