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

前端 未结 7 1360
失恋的感觉
失恋的感觉 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条回答
  •  迷失自我
    2021-02-07 08:54

    Header files in C/C++ has nothing to do with classes or interefaces at all.

    A header file is more like the reference you add to your poject or the using statement.

    Its an instruction to the compiler that the objects and function declarations in the header file exists so that the compiler can compile the file without having to look through the whole project.

    A header file in C++ can Contain classes or function definitions or macros or enums or many other things but is conceptually very different from classes or interfaces.

    You can use interface in C++ to How do you declare an interface in C++? and those definitions are placed in header files, but the header file in it self is something else.

    The reason to use interface instead of inheritance is that many classes can implement an interface or many interfaces but you can only inherit from one class.

    So if you have many objects that is to be interchangeable you would end up with a very complex class hierarchy while with interfaces the classes can be built completely separate with only the interface linking them .

提交回复
热议问题