Start learning free

LESSON 186 OF 344 · OBJECT-ORIENTED PROGRAMMING

Interfaces in Java: Contracts with implements

Lesson Read the full explanation

TL ; DR:

An interface is a pure contract — a list of methods that a class promises to implement, with no shared data and no shared code. Unlike inheritance ("is a"), interfaces express "can do".


interface Speaker {
    void speak();
}
class Dog implements Speaker {
    @Override
    public void speak() {
        System.out.println("Woof");
    }
}


Full lesson:

An interface defines what a class can do, not how it does it or what it is. A Truck, a Robot, and a Drone aren't the same kind of thing — but they can all Move(). You'd put Move() in a Movable interface and have each one implement it.

Interface vs abstract class

Abstract classInterface
Has fieldsYesUsually no
Has method bodiesYes (some)No (or default impls only)
Multiple "inheritance"Usually noYes — a class can implement many interfaces
Models"is a""can do"

A class inherits from at most one parent class but can implement many interfaces. That's why interfaces are the right tool for cross-cutting capabilities like Comparable, Serializable, Iterable, etc.

The language landscape

  • C# / Java — first-class interface keyword. C# uses : for both inheritance and implementation; Java uses extends for inheritance and implements for interfaces.
  • Python — no separate interface; abstract base classes (ABCs) with all-abstract methods serve the same role.
  • JavaScript — no interface keyword in plain JS (TypeScript has it). The convention is a stub class.
  • C++ — a class with only pure-virtual methods is an interface. Multiple inheritance lets a class implement several.

Your task

The Speaker interface (or interface-like base) is already declared. Create a Dog class that implements it, with a speak() method that prints "Woof".

Expected output:

Woof
STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · OBJECT-ORIENTED PROGRAMMING

    Interfaces in Java, explained

    What an interface is

    An interface is a contract: a list of methods that a class promises to provide. It says what an object can do, and it leaves out how the object does it. A Truck, a Robot and a Drone have little in common as types, but all three can move. Put move() in a Movable interface, let each class implement it, and code that only needs something movable can work with all three.

    Inheritance models "is a": a Dog is an Animal. An interface models "can do": a Dog can speak. That difference decides when to use which.

    Syntax

    You declare an interface with the interface keyword. Its methods have no body, just a signature ending in a semicolon. A class signs the contract with implements:

    interface Speaker {
        void speak();
    }
    
    class Dog implements Speaker {
        @Override
        public void speak() {
            System.out.println("Woof");
        }
    }
    

    Once Dog implements Speaker, a Dog can be stored in a variable of type Speaker. The code that uses the variable only knows about speak():

    Speaker rex = new Dog();
    rex.speak();
    
    Woof
    

    Writing code against the interface type, not the concrete class, is the main payoff. A new class that implements Speaker works in the same code without any change to it.

    Interface or abstract class

    Abstract classInterface
    Models"is a""can do"
    Instance fieldsYesNo (only constants)
    Method bodiesYes, for some methodsOnly default, static and private methods
    Parents a class can haveOneAny number

    A class extends at most one parent class, but it can implement as many interfaces as it needs. That is why Java uses interfaces for capabilities that cut across unrelated classes, such as Comparable and Iterable. To implement several, separate them with commas:

    interface Mover {
        void move();
    }
    
    class Robot implements Speaker, Mover {
        @Override
        public void speak() { System.out.println("Beep"); }
        @Override
        public void move() { System.out.println("Rolling"); }
    }
    

    A class can combine both keywords, with extends first: class Dog extends Animal implements Speaker.

    Details that trip people up

    • Interface methods are public. A method declared in an interface is implicitly public, so the implementing method must be declared public too. Leaving the modifier off gives a compile error about weaker access privileges.
    • Implement every method. A concrete class that implements an interface must provide all of its abstract methods. A missing one is a compile error. An abstract class can leave some of them for its subclasses.
    • @Override is optional but worth writing. It asks the compiler to check that the method really matches one from the interface. A typo such as spek() then fails to compile instead of quietly adding a new method.
    • Default methods. Since Java 8 an interface can carry a method body if you mark it default. Implementing classes inherit it and may override it:
      interface Mover {
          void move();
          default void stop() {
              System.out.println("Stopped");
          }
      }
      
      This still holds no per-object data. A default method can only call the interface's other methods.
    • You can't instantiate an interface. new Speaker() doesn't compile on its own. You create an object of a class that implements it, or an anonymous class, or a lambda for an interface with exactly one abstract method: Speaker s = () -> System.out.println("Hi");.

    The exercise

    The Speaker interface is already declared. The task is to add a Dog class that implements it, with a speak() method that prints Woof, so that mainFunction prints that line.

    1. Declare the class. Below the interface, write class Dog implements Speaker. Use implements here, not extends, because Speaker is an interface.
    2. Implement the method. Inside Dog, write public void speak() with @Override above it, and print the text with System.out.println. The method has to be public because the interface's method is.

    The finished code:

    interface Speaker {
        void speak();
    }
    
    class Dog implements Speaker {
        @Override
        public void speak() {
            System.out.println("Woof");
        }
    }
    
    class Solution {
        public void mainFunction() {
            Speaker rex = new Dog();
            rex.speak();
        }
    }
    

    In mainFunction, the variable rex has the type Speaker, while the object is a Dog. Java picks the method from the actual object at run time, so the call prints Woof.

    Key takeaways

    • An interface lists methods a class promises to provide. It says what, not how.
    • Use implements for interfaces and extends for a parent class.
    • A class can implement many interfaces but extend only one class.
    • Implementations of interface methods must be public.
    • Write code against the interface type so that new implementations plug in unchanged.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free