jht
jht

Reputation: 605

How can a null reference to an interface return a value?

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 ?

Upvotes: 7

Views: 1282

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

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

Upvotes: 20

Related Questions