Labs ICT
โญ Pro Login

Interfaces

A class can only extend one parent class. Java does not allow multiple inheritance โ€” it causes too many headaches. But what if you want a class to have multiple sets of behaviors? That is where interfaces come in.

An interface is like a contract. It says "any class that implements me must have these methods." It does not tell you how to implement them โ€” that is up to the class.

Defining an Interface

You use the interface keyword instead of class. Inside, you declare method signatures without bodies.

interface Flyable {
  void fly();
}

interface Swimmable {
  void swim();
}

These interfaces say "if you want to be flyable, you need a fly() method. If you want to be swimmable, you need a swim() method." The details are up to whoever implements them.

The implements Keyword

A class uses implements to promise it will provide the methods defined in the interface. A class can implement multiple interfaces.

interface Flyable {
  void fly();
}

interface Swimmable {
  void swim();
}

class Duck implements Flyable, Swimmable {
  public void fly() {
    System.out.println("Duck is flying");
  }

  public void swim() {
    System.out.println("Duck is swimming");
  }
}

public class Main {
  public static void main(String[] args) {
    Duck d = new Duck();
    d.fly();
    d.swim();
  }
}

Duck implements both Flyable and Swimmable. Java forces the Duck class to provide actual code for both fly() and swim(). If it forgets one, the code will not compile.

Why Interfaces Matter

Interfaces let you write flexible code. You can write a method that accepts any Flyable instead of a specific class.

interface Flyable {
  void fly();
}

class Bird implements Flyable {
  public void fly() {
    System.out.println("Bird flaps wings");
  }
}

class Airplane implements Flyable {
  public void fly() {
    System.out.println("Airplane uses engines");
  }
}

public class Main {
  public static void main(String[] args) {
    Flyable f1 = new Bird();
    Flyable f2 = new Airplane();
    f1.fly();
    f2.fly();
  }
}

Both Bird and Airplane are Flyable. They both have a fly() method, but they work completely differently. The interface guarantees the method exists, but does not care how it works.

๐Ÿงช Quick Quiz

What keyword do you use to implement an interface?