Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 ?

like image 506
jht Avatar asked Jan 14 '15 17:01

jht


People also ask

Can an interface be null?

Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface.

What does null return mean?

null return means a return which indicates that no transaction was made by the registered person during the tax period and no amount of tax is to be paid or refunded. Sample 1.

Does interface return anything?

Returning interface allows a member function to return reference of any implemented class. It gives flexibility to program to an interface and also is helpful in implementation of factory and abstract factory design pattern.


1 Answers

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
like image 170
Sotirios Delimanolis Avatar answered Jan 04 '23 05:01

Sotirios Delimanolis