Skip to content

Interfaces & Polymorphism

The Course
•
20 min study

An interface states what an object can do without choosing how it does it. You have already used List as a library contract. Now write a small contract of your own. Polymorphism means that the same call can use different implementations while the caller keeps the same code.

Work through the example

The interface declaration contains a method signature ending in ;, with no method body. It describes an operation; the implementing classes provide the bodies. You cannot create new Formatter() directly.

implements promises that a class supplies the interface's methods. An interface method such as String format(String title) is public; the implementation must therefore also be public. @Override catches a misspelling or wrong signature.

The variable's interface type controls which operations a caller can request. The actual object chooses the method body at runtime. printTitle does not inspect class names or cast to a specific implementation. That separation is useful only if implementations keep the same behavioral promise: here every nonnull title becomes readable text.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        printTitle(new PlainFormatter(), "Read");
        printTitle(new BracketFormatter(), "Read");
    }

    static void printTitle(Formatter formatter, String title) {
        System.out.println(formatter.format(title));
    }
}

interface Formatter {
    String format(String title);
}

final class PlainFormatter implements Formatter {
    @Override
    public String format(String title) {
        return title;
    }
}

final class BracketFormatter implements Formatter {
    @Override
    public String format(String title) {
        return "[" + title + "]";
    }
}
Check your prediction
Text
Read
[Read]

Compare the behavior

A contract includes meaning, not just a method name. A MinutesRule answers whether a duration is accepted. The two implementations represent different policies, but both interpret true as accepted and neither changes external state. A caller can apply either policy through one method.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        System.out.println(allowed(new PositiveRule(), 10));
        System.out.println(allowed(new ShortRule(), 40));
    }

    static boolean allowed(MinutesRule rule, int minutes) {
        return rule.accepts(minutes);
    }
}

interface MinutesRule {
    boolean accepts(int minutes);
}

final class PositiveRule implements MinutesRule {
    public boolean accepts(int minutes) {
        return minutes > 0;
    }
}

final class ShortRule implements MinutesRule {
    public boolean accepts(int minutes) {
        return minutes > 0 && minutes <= 25;
    }
}
Check your prediction
Text
true
false

Trace the call through the contract type

Follow printTitle(new BracketFormatter(), "Read"). The parameter formatter has declared type Formatter, which exposes format. The actual receiver is a BracketFormatter, so its implementation supplies the body. The caller does not need a separate branch to identify the class.

A shared signature is only the structural part of the contract. Every implementation also needs to agree on accepted inputs, returned meaning and effects. If one TitleRule returns false for null while another throws unexpectedly, the caller cannot use them interchangeably under a return-false contract. Test both implementations with the same boundary cases.

An interface is useful where a caller needs interchangeable behavior or a clear boundary. It is not a requirement to create two names for every class. Keep the interface small enough that a consumer can use it without knowing the private implementation or downcasting to a particular class.

Practice independently

Exercise

Interfaces & Polymorphism: practice

Define TitleRule with boolean accepts(String title). Implement NonblankRule and LongRule (at least four trimmed characters). Both must return false for null (not throw); false means the title does not satisfy the rule. Write one show(TitleRule, String) caller. Print results for nonblank " Go ", long " Go ", and long " Java ".

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Implement the contract and two policies");
    }
}
Hint 1: the idea

The caller should depend on TitleRule, not on either concrete class.

Hint 2: a first step

Write the method signature once in the interface and give both classes public implementations.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
public class Main {
    public static void main(String[] args) {
        show(new NonblankRule(), " Go ");
        show(new LongRule(), " Go ");
        show(new LongRule(), " Java ");
    }

    static void show(TitleRule rule, String title) {
        System.out.println(rule.accepts(title));
    }
}

interface TitleRule {
    boolean accepts(String title);
}

final class NonblankRule implements TitleRule {
    public boolean accepts(String title) {
        return title != null && !title.trim().isEmpty();
    }
}

final class LongRule implements TitleRule {
    public boolean accepts(String title) {
        return title != null && title.trim().length() >= 4;
    }
}

Expected output:

Text
true
false
true

Change it and test again

Add a third implementation that accepts only titles beginning with "Read". Reuse the same show method unchanged. Test null, blank text and the minimum accepted length. If show needs an instanceof test for each policy, revisit the interface boundary.

Explain before moving on

Which method body runs when an interface variable holds a LongRule? Why must the implementation method be public even when the class itself has no public modifier?

Was this article helpful?

Your response is saved on this device.