Intermediate 8 min

Interfaces and polymorphism

An interface describes behavior that several classes can provide in their own way.

How it works

Read the interface as a promise to a caller. It says what arguments can be passed and what result to expect. The caller can ask both formatters to format Mira with the same call, even though each formatter works differently. This keeps the caller independent of how the result was made.

Walk through an example

A Formatter interface can declare format(String name). A plain formatter can return the name, while a greeting formatter can return Hi followed by the same name.

What to watch for

Choose interfaces around small useful behavior. Callers that only need formatting should not have to know each implementation’s fields.

Code example

public class Main {
    interface Formatter { String format(String name); }

    public static void main(String[] args) {
        Formatter greet = name -> "Hi " + name;
        System.out.println(greet.format("Mira"));
    }
}

Check your understanding

What string does this implementation return?

See the example and explanation
Worked example
Given Formatter f = name -> "Hi " + name; f.format("Mira")
Answer Hi Mira

The selected formatter adds its prefix to the supplied name.

Open practice problem
Next lessonGenerics and type parameters