CodeBlanks Logo Icon CodeBlanks

implements

Learn to fulfill contracts with implements.

Implementing with implements

A class implements an interface with the implements keyword. The class must write every method in the interface; otherwise you get a compile error.

Example: class Circle implements Drawable { public void draw() { ... } }. Here Circle fulfills the contract; it writes draw with its body. The implements keyword comes after the class name and before the interface name. The implemented method must be public; because interface methods are implicitly public. This mechanism lets different classes share the same surface.

The override requirement

A class that implements an interface must write all its methods; otherwise you get a compile error. Java requires the contract to be fully fulfilled. This makes incomplete implementation noticeable.

Example: if you define interface Speaker { void speak(String msg); void greet(); }, the implementing class must write both speak and greet. Forget one and the compiler gives an error like 'Circle is not abstract and does not override the abstract method greet'. The @Override annotation goes above the method; it warns you if the signature is wrong. This check keeps code aligned with the contract.

Practice Implement the Speaker interface

Define an interface Speaker; add the void speak(String msg) signature. Then write class Person implements Speaker; write the public void speak(String msg) method with a body that runs System.out.println("Speaking: " + msg);. In main call new Person().speak("Hello").

Starter code

Main.java
// Define the Speaker interface
// Write Person implements Speaker
// Call new Person().speak("Hello") in main

Sample solution

Main.java
interface Speaker {
    void speak(String msg);
}
class Person implements Speaker {
    public void speak(String msg) {
        System.out.println("Speaking: " + msg);
    }
}
class Main {
    public static void main(String[] args) {
        new Person().speak("Hello");
    }
}

Expected output

Speaking: Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the implementation parts

Term Meaning
implements Implementation keyword
public void draw() Written method
Circle Implementing class
Drawable Implemented interface

2 What happens if a class does not write one interface method?

  • It warns but compiles
  • It gives a compile error Correct answer
  • It errors at runtime
  • The method is auto-added

Explanation: the contract is incomplete.

3 Complete the implements line

Question
class Square ____ Drawable {
    public void draw() { }
}
Answer
class Square implements Drawable {
    public void draw() { }
}

Explanation: The implements keyword implements an interface.

All lessons in Intermediate