variable of Interface type

后端 未结 3 1625
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 09:01

I am learning Java, I saw the following description regards to interface in a book:

When a variable is declared to be of an interface typ

3条回答
  •  无人及你
    2021-02-04 09:31

    You cannot instantiate an interface. But you may type your variable with the interface name:

    Myinterface foo = new MyObject();
    

    Assuming MyObject implements MyInterface.

    It may be useful when acquiring objects from an external source, for instance.
    In such a case, you don't know (and don't care) about the real type of the object.

    You only need to know and ensure it implements some interface, so you can call interface methods on the object.

    Assuming you have the following variable:

    Myinterface foo;
    

    And two classes (Foo and Bar), both implementing MyInterface.
    You will then be able to assign the foo variables with instances of both Foo and Bar.

    The same applies to methods arguments, of course.

提交回复
热议问题