Back to course

Abstraction using Interfaces (and Default Methods)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 25: Abstraction using Interfaces

An Interface is another way to achieve 100% abstraction in Java. It is a blueprint of a class that defines a contract: any class implementing the interface must define the methods declared within it.

1. Key Characteristics of Interfaces

  1. Defined using the interface keyword.
  2. A class uses the implements keyword to adopt an interface.
  3. Interfaces support multiple inheritance (a class can implement multiple interfaces).
  4. Before Java 8, all methods in an interface were implicitly public and abstract.

java public interface Swimmer { // Interface // All methods are public abstract by default void swim(); void dive(int depth); }

public class Dolphin implements Swimmer { @Override public void swim() { System.out.println("Dolphin swims gracefully."); }

@Override
public void dive(int depth) {
    System.out.println("Diving to " + depth + " meters.");
}

}

2. Default Methods (Java 8+)

Before Java 8, if you added a new method to an interface, every implementing class would break. Default methods solve this by allowing methods with a body in the interface itself.

java public interface Swimmer { void swim();

// Default method: provides a default implementation
default void checkStatus() {
    System.out.println("Swimmer status: OK");
}

}

// Dolphin does not need to implement checkStatus() unless it wants to override it.

3. Interfaces vs. Abstract Classes

FeatureInterfaceAbstract Class
InheritanceMultiple (implements)Single (extends)
ConstructorsCannot have constructorsCan have constructors
FieldsOnly public static finalCan have any type of field
Abstraction Level100% (mostly)0% to 100%

Use Case: Use Interfaces when defining a capability or contract (e.g., Runnable, Comparable). Use Abstract Classes when providing a base implementation for a closely related set of classes (e.g., Shape, Employee).