Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

file Controller.java:

interface Controller {...}

file ControllerImpl.java:

class ControllerImpl implements Controller {...}

But for every interface there is only one implementation. Isn't that the same as using header files in C/C++ where I have the code split into files like

Controller.hpp
Controller.cpp

From what I know, header files in C/C++ have been introduced to help the compiler, which is not necessary anymore in Java. Also header files should help with the readability of the code, but having a modern IDE with folding and outline view this is also not a necessity anymore.

So why do people again introduce header files in Java through the back door by programming against interfaces?

like image 444
asmaier Avatar asked Feb 18 '11 10:02

asmaier


2 Answers

No. In C++, files (headers) are not the same as classes.

Programming against interfaces as in Java can be done in C++, too, by programming against abstract base classes.

However, the Java term of "interface" is quite restricted. Basically, any function declaration is an interface:

void call_me(int times); 

As are, of course, classes and other types.

In C++, you group such things in headers, so an interface can consist of one header. However, it might just as well consist of multiple headers.

like image 80
sbi Avatar answered Sep 28 '22 01:09

sbi


Interfaces doesn't come from a desire to keep header files.

Interfaces the closest Java comes to supporting http://en.wikipedia.org/wiki/Design_by_contract

like image 20
Peter Lawrey Avatar answered Sep 28 '22 02:09

Peter Lawrey