Java Learner logo

Module 6: Inheritance and Polymorphism

Lesson focus

Interfaces

Understand interfaces as a pure contract of behaviors. Learn how a class can implement multiple interfaces to achieve a form of multiple inheritance.

What is an Interface? An interface is a completely abstract type that is used to group related methods with empty bodies. It is a contract that specifies what a class can do, without saying how it will do it.

Key Rules:

  • An interface is declared using the interface keyword.
  • All methods in an interface are implicitly public and abstract (you don't need to type the keywords).
  • A class uses the implements keyword to use an interface.
  • A class can implement multiple interfaces. This is how Java achieves a form of multiple inheritance.
  • A class that implements an interface must provide an implementation for all of its methods.

Interface vs. Abstract Class:

  • Abstract Class: Can have both abstract and concrete methods. A class can only extend one abstract class. Represents an 'is-a' relationship.
  • Interface: Can only have abstract methods (with some exceptions in modern Java like default methods). A class can implement many interfaces. Represents a 'can-do' relationship (e.g., a Car and a Bird can both implement the Movable interface).

Default Methods (Java 8+): Modern interfaces can provide a default implementation for a method using the default keyword. This allows new methods to be added to interfaces without breaking existing classes that implement them.

interface Drawable {
    void draw(); // public and abstract by default
}

interface Clickable {
    void onClick();
}

// This class implements two interfaces
class Button implements Drawable, Clickable {
    @Override
    public void draw() {
        System.out.println("Drawing a button.");
    }

    @Override
    public void onClick() {
        System.out.println("Button clicked!");
    }
}

Lesson quiz

What keyword does a class use to adopt an interface?

Next lesson →