Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating the interface from an implementation in Java

Tags:

java

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?

like image 835
Beyond Noob Avatar asked Apr 21 '26 06:04

Beyond Noob


1 Answers

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.

  • A single class may implement multiple interfaces, and multiple classes may a single interface
  • Member values are not included in an interface, only methods.
  • Only public methods appears in a Java interface.
  • No implementation is ever allowed in an interface (as opposed to C++ templates, which depend on .h implementation).

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).

like image 159
Paul Draper Avatar answered Apr 23 '26 20:04

Paul Draper