简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM