An interface defines a set of methods that any class that implements it has to have. We use class Test implements Tester {}; to define such a relationship.

Like abstract classes, an interface cannot be instantiated directly, only through subtyping. But they don’t define any behaviour but only method signatures.

Declaration

public interface TestInterface {
	public void method(int test);
	...
} 

All methods are public (doesn’t have to be explicit). Any attributes must be public and final.

Implementation

All implementations of an interface using implements must instantiate all methods declared by the interface (except if the class is abstract), otherwise we get a compiler error.

Any class that extends a class that implements an interface also implements that interface. We can make that explicit using a redundant implements. We can then also override those methods in the subclass:

Note that a class can implement multiple interfaces. If a method is defined in multiple of those interfaces, it of course has to implemented only once.

Interface extends Interface

interface I {
	public void method();
}
 
interface J extends I (or also multiple A, B, C) {
	public void method2();
}

Note that J cannot override any of I’s declarations, only:

  • remove exceptions
  • narrow the type returned: from Object to String for example
  • Default implementation
interface B {
    Object getValue();
    void process() throws IOException;
}
 
interface A extends B {
    // 1. Covariant return type - more specific than Object
    String getValue();  // Valid override
    
    // 2. Can reduce or eliminate exceptions
    void process();  // Valid - removes IOException
    
    // 3. Can add default implementation
    default String getValue() {
        return "default";
    }
}