Syllabus / Java / Phase 3: Object-Oriented Programming (Days 11–16)
Intermediate

Interfaces

📂 Phase 3: Object-Oriented Programming (Days 11–16) · Java

An interface is a fully abstract contract — it defines what methods a class must implement, without specifying how. It's how Java achieves complete abstraction and a form of multiple inheritance.

Defining and Implementing an Interface

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

class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

class Square implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a square");
    }
}

Why Interfaces Solve the Multiple Inheritance Problem

A class can implement multiple interfaces, unlike extending multiple classes:

interface Drawable {
    void draw();
}
interface Resizable {
    void resize(double factor);
}

class Shape implements Drawable, Resizable {
    public void draw() {
        System.out.println("Drawing shape");
    }
    public void resize(double factor) {
        System.out.println("Resizing by " + factor);
    }
}

Since interface methods have no body to conflict with, there's no diamond-problem ambiguity even when implementing several interfaces.

Interfaces vs Abstract Classes

AspectInterfaceAbstract Class
MethodsAll abstract (default/static methods allowed since Java 8)Mix of abstract and concrete
FieldsOnly public static final (constants)Any type of field
Multiple inheritanceA class can implement manyA class can extend only one
ConstructorsNot allowedAllowed

Default Methods (Java 8+)

Interfaces can now provide a default implementation, which implementing classes may override if needed:

interface Greetable {
    default void greet() {
        System.out.println("Hello!");
    }
}

class Person implements Greetable {
    // can use the default greet(), or override it
}

new Person().greet(); // Hello!

Polymorphism Through Interfaces

Drawable[] shapes = { new Circle(), new Square() };
for (Drawable d : shapes) {
    d.draw(); // calls the correct implementation for each object
}
Interview tip: "Can an interface extend another interface?" — Yes, using extends, and an interface can extend multiple interfaces at once (unlike classes, which can only extend one class).