What is an interface in Java, and what does it guarantee to the code that uses it?
An interface is a named contract. It lists the operations a type promises to support without providing an implementation of them, so it describes what a collaborator can do and nothing about how. A class that implements it is bound by that promise, and the compiler checks the promise at build time.
public class Main {
public static void main(String[] args) {
Greeter g = new FormalGreeter();
System.out.println(g.greet("Ada"));
Greeter h = new CasualGreeter();
System.out.println(h.greet("Grace"));
}
}
interface Greeter {
String greet(String name);
}
class FormalGreeter implements Greeter {
public String greet(String name) { return "Good day, " + name; }
}
class CasualGreeter implements Greeter {
public String greet(String name) { return "Hey " + name; }
}The example shows the guarantee in action. Both greeters satisfy the same contract, and the caller holds a Greeter reference in both cases. The output differs, and the caller has no way to tell from the code which implementation it received, nor does it need to. That is the point of the contract: the call site is written once and works for every implementation.
Because the interface is the shared vocabulary, the caller's knowledge is bounded. When a new greeting style appears, you add a class and the caller is untouched. If instead the caller had depended on the concrete classes, adding one would have meant editing every place that used them.
What the interface does not give you is a guarantee about implementation. It says nothing about thread safety, about performance, or about whether two implementations behave identically in edge cases. Those are the guarantees you have to document or design for separately, and knowing the difference between a promised contract and an accidental behaviour is what separates a careful answer from a recited one.