Is programming against interfaces in Java the same concept as using header files in C/C++?

前端 未结 7 1380
失恋的感觉
失恋的感觉 2021-02-07 08:02

The java code I\'m working on at the moment has often a structure like

file Controller.java:

interface Controller {...}

file Controller

7条回答
  •  Happy的楠姐
    2021-02-07 08:39

    In Java, an interface defines a contract, while a class provides an implementation of a contract.

    Most contracts have only one meaningful or relevant implementation; some even assume a specific implementation and do not allow any other. Those contracts and their implementations are defined together in classes, without any interfaces. Example: java.lang.String.

    On the other hand, some contracts do not make any assumption on the possible implementations. Those are defined in interfaces. Partial implementations can be defined in abstract classes, and typical complete implementations can be defined in classes, but the fact that the contract is defined in an interface allows you to write your own implementation of that contract and use it wherever an instance of the contract is expected.

    At the file level, both an interface and a class are compilation units and deserve their own file.

    As you now hopefully understand, the distinction between header files and implementation files in C++ is very different.

提交回复
热议问题