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 ?

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
"Fields declared in interfaces are implicitly static" and final.
I believe Eclipse even issues a warning when you do that, it's a bad practice in general (though sometimes it's desirable)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.