1

I come from a C++ background and am trying to learn Java now . For C++ classes , we often split the interface and implementation files into foo.h and foo.cpp respectively. After which we would link the files using the #include statement

For Java , how do i split the interface and implemenation into two separate files similar to what I have done in C++ , what are the steps to be taken ??

Computernerd
  • 7,378
  • 18
  • 66
  • 95

3 Answers3

1

In Java there's no such distinction.

The closest thing you can do is to have a strict separation of interfaces and implementation of interfaces (something usually recommended).

so for example you can have a

IMyInterface.java

public interface IMyInterface {

}

and a MyImplementation.java

public class MyImplementation implements IMyInterface {

}

However... this is not the same.... it is more like C++ abstract classes and C++ implementation classes.

jsantander
  • 4,972
  • 16
  • 27
0

There's the interface keyword which allows you to declare the public API, which the implementing class can use implements to leverage. This is as close as you can get to your desired separation. Java is simply designed differently, there is no such thing as header files. Header files do not serve as interfaces in c++ anyways, they're just the compiler-required units so the compiler knows where to find method signatures.. The more correct equivalent in C++ for the concept of an interface is the abstract base class.

For the answer to why... well, I'll just direct you to this already-answered question here

Community
  • 1
  • 1
TTT
  • 1,952
  • 18
  • 33
0

... we often split the interface and implementation files into foo.h and foo.cpp ...

That's not true, you are confusing the terms class declaration and (abstract) interface.

Java has no concept of header files, nor does it distinguish class declaration from class definition.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190