How can you separate the interface from an implementation in Java?
In C/C++, this can be done by creating 2 files a .c and .h file with the same file name. How can you do this in Java?
The closest analogy to .h and .c separation is interfaces.
MyInterface.java
interface MyInterface {
void doSomething();
}
MyImplementation.java
class MyImplementation implements MyInterface {
public void doSomething() {
System.out.println("Hello world");
}
}
You then use the interface type everywhere except for the actual constructor
MyInterface instance = new MyImplementation();
Of course, there are several differences.
But this is how "programming to interfaces" is accomplished.
There is no consistent convention for naming interfaces vs concrete classes in Java. C# (nearly identical in its treatment of interfaces) has a convention which I have come to use where the interface begins with I, e.g. IList. The Java standard libraries tend to use the "pure" name for the interface, and then modify it for the concrete implementation, such as List (interface) and ArrayList (implementation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With