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

前端 未结 7 1379
失恋的感觉
失恋的感觉 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 09:01

    The question is good, there is a connection between header files and classes/interfaces/OO programming, beyond the raw syntax of the languages.

    Proper C++ program design:

    • Put one class declaration, and one only, in a h-file.
    • Give said h-file the same name as the class declared.
    • Put the class definition in a cpp-file with the same name as the h-file.

    Proper Java program design:

    • Same as for C++, though also put interfaces in files of their own.

    Proper C design:

    • In the h-file, declare functions belonging to a particular "code module".
    • Put the function definitions in a c-file with the same name as the h-file.
    • All variables you would have declared as private/protected if writing C++/Java should either be truly private through the concept of "opaque type/pointers", or be placed at file scope and declared static, so that they can be shared between functions within the "code module" (though that makes the code non-reentrant).

    If you don't use the above intimate connection between classes and h-files, there is a fine chance that your program is an unreadable mess, no matter how elegant your OO design is.

提交回复
热议问题