Object-Oriented JavaExtra· 30 min read

Interfaces

An interface is a contract: a list of methods a class promises to provide.

What you will learn

  • Define an interface
  • Implement it in a class
  • See why interfaces give flexibility

A contract of abilities

An interface lists method names with no code inside — just a promise. Any class that implements the interface must provide the actual code for those methods. Think of it as a contract: sign it, and you agree to deliver these abilities.

An interface listing two required methods
public interface Playable {
    void play();    // no body — just the promise
    void stop();
}

Note: Output: (No output — an interface has no code to run. It only states which methods an implementing class must provide.)

A class fulfils the contract

MusicPlayer implements Playable and provides the methods
public class MusicPlayer implements Playable {
    @Override
    public void play() {
        System.out.println("Playing music...");
    }

    @Override
    public void stop() {
        System.out.println("Music stopped.");
    }
}

Note: Output: (No output yet — the class now fulfils the contract by writing real code for play() and stop(). If it left one out, Java would refuse to compile.)

Using it

Treat any Playable the same way
public class Main {
    public static void main(String[] args) {
        Playable device = new MusicPlayer();
        device.play();
        device.stop();
    }
}

Note: Output: Playing music... Music stopped. Notice the variable type is Playable (the interface), but the real object is a MusicPlayer. Any class that implements Playable would work here — that is the flexibility interfaces give.

Interface vs inheritance

Inheritance (extends)Interface (implements)
Says: a Dog IS AN AnimalSays: a class CAN DO these things
Shares actual codeShares only a promise (the method list)
One parent onlyA class can implement MANY interfaces

Tip: A class can implement several interfaces at once: class Phone implements Playable, Recordable. This is how Java lets one class take on many roles without the limits of single inheritance.

Q. What must a class do when it implements an interface?

Answer: An interface only lists method names. The implementing class must supply the actual code for each one, or it will not compile.

✍️ Practice

  1. Define an interface Shape with a method area() and implement it in a Circle class.
  2. Create a Circle through a Shape variable and call area().

🏠 Homework

  1. Create a Drawable interface with a draw() method and have two different classes implement it. Call draw() on each.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →