What is an interface in Java, and what does it guarantee to the code that uses it?
An interface in Java is a list of method signatures with no code behind them. It is the promise that a class makes about what it can do, without saying anything about how.
public class Main {
public static void main(String[] args) {
Greeter g = new FormalGreeter();
System.out.println(g.greet("Ada"));
}
}
And here is the interface and the implementation.
public interface Greeter {
String greet(String name);
}
public class FormalGreeter implements Greeter {
@Override
public String greet(String name) {
return "Good day, " + name;
}
}
So what does it guarantee to the code that uses it? Four things.
the guarantee what it means
------------------------------------- --------------------------------------------
the methods are there the compiler checks that every
implementation has them
the behaviour can differ each implementation answers in
its own way
the caller cannot reach inside the interface has no fields and
the implementation's fields are
not visible
the implementation can change the caller only depends on the
interface
And the first one is the one that the compiler gives you. If a class says it implements the interface then the compiler checks that every method is there with the right name, the right parameters and the right return type. So a class that does not do what it promised does not compile.
// This does not compile. The greet method is missing.
public class CasualGreeter implements Greeter {
}
And the second one is the interesting one. The interface does not say what the greeting is, only that there is one. So the caller asks for a greeting and gets whatever the implementation decides, and the caller does not have to know which implementation it has.
And there is one more thing that is worth knowing about, and it is about what an interface cannot do. It cannot hold state. It cannot have instance fields. So an interface is a set of promises about behaviour and never about data.
// This does not compile. An interface cannot have an
// instance field.
public interface Greeter {
String greet(String name);
int count = 0;
}
And since Java 8 an interface can have default methods and static methods, so it can have a little code. But the state is still not allowed, and that is what keeps it different from an abstract class.
So the rule to remember is this. An interface is a promise about behaviour with no state behind it.
The next two questions in this topic are about the difference from an abstract class and about the benefits and the costs.