0Pricing
Java Academy · Lesson

Interfaces (intro & contrasts)

Define interfaces, implement them in classes, and contrast with abstract classes. Learn default methods and multiple implementation.

What is an interface?

Interface: a contract that lists method signatures a class must provide. Use it to describe capability, like Drivable or Printable, without fixing class hierarchies.

Code: implement an interface

Classes implement interfaces to promise certain behavior. You can reference the object by its interface type and call the declared methods.

public class Main {
  // Interface that declares a capability
  static interface Drivable {
    void drive(); // method to implement
  }

  // A class implements the interface
  static class Car implements Drivable {
    public void drive() {
      System.out.println("Car is driving");
    }
  }

  public static void main(String[] args) {
    Drivable d = new Car(); // upcast to interface
    d.drive();              // runs Car's method
  }
}

All lessons in this course

  1. Abstract Classes
  2. Interfaces (intro & contrasts)
  3. Up/Down Casting & instanceof
← Back to Java Academy