lovespring
lovespring

Reputation: 440

Strange behavior, about Interface to be a member of a class in Java

interface SomeInterface {
    String test = "hello";
}

public class SomeCls {
    SomeInterface sif;
    public static void main(){
        SomeCls cls = new SomeCls();
        cls.sif = null;
        System.out.println(cls.sif.test); // still work.
    }
}

I'm coming from c++, question is:

1) because interface is a "abstract" type, how can it be used as a member, I mean, how to init it?

2) I know, the member "sif" may be just a reference(not like the c++ reference, more like a pointer in c), but since I set it reference to null. how can it still output the interface's field?

Upvotes: 0

Views: 104

Answers (2)

Ken Bekov
Ken Bekov

Reputation: 14015

About your first question.

You can't create instance of interface. But you can create implementation of interface:

public class SomeClass implements SomeInterface{
   ...
}

And as you correctly noted, variable of interface type "may be just a reference"

SomeInterface sif = new SomeClass();

You can consider interface like a contract, description of behavior, that class (witch implements this interface) promise to provide.

Another point, there is no multiple inheritance in Java, but class can implement multiple interfaces.

Upvotes: 1

Rahman
Rahman

Reputation: 3785

Variable declared inside an interface would be static by default. So it doesnt make sense to call that variable using reference .

You can call like SomeInterface.test

Upvotes: 4

Related Questions