Interfaces

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • An Interface is a completely abstract “contract” that classes can implement.
  • A class can implement multiple interfaces, which is Java’s workaround for the lack of multiple class inheritance.
  • By default, all methods in an interface are public abstract, and all fields are public static final (constants).

Concept

Interfaces define what a class must do, but not how it does it. If a class claims to implement an interface, it signs a contract guaranteeing it will provide the code for every abstract method defined in that interface.

(Note: Since Java 8, interfaces can have default and static methods with bodies. Since Java 9, they can have private methods).

Examples

// The Interface (The Contract)
interface Flyable {
    // public static final by default
    int MAX_SPEED = 900; 
    
    // public abstract by default
    void fly(); 
}

interface Navigable {
    void navigate();
}

// A class implementing MULTIPLE interfaces
class Airplane implements Flyable, Navigable {
    @Override
    public void fly() {
        System.out.println("Jet engines roaring. Taking off!");
    }
    
    @Override
    public void navigate() {
        System.out.println("Using GPS routing.");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        // Programming to an interface
        Flyable myPlane = new Airplane();
        myPlane.fly();
    }
}

Interview Questions

Q: If an interface only has abstract methods, what was the point of adding default methods in Java 8?
A: default methods were introduced for backward compatibility. Imagine a library with an Interface used by thousands of clients. If the library author adds a new method to the interface, it breaks the code of every single client (because they are forced to implement the new method). By making the new method default, the author provides a fallback implementation, so existing clients don’t break, while allowing new clients to override it.

Q: Can an interface implement another interface?
A: No. An interface cannot implement another interface, but it can extend another interface (or even multiple interfaces).

interface Animal {}
interface Pet {}
interface Dog extends Animal, Pet {} // Valid!