R
Rishtaara
Java Fundamentals
Lesson 22 of 36Article17 min

Interface & Anonymous Classes

interface defines what a class must do — method signatures without implementation (before Java 8).

Interface — contract of methods

interface defines what a class must do — method signatures without implementation (before Java 8).

class implements Interface. A class can implement many interfaces.

Real-life example: USB port is an interface — any device with USB plug must fit the same shape and rules.

Interface and implements
interface Printable {
    void print();
}

class Report implements Printable {
    @Override
    public void print() {
        System.out.println("Printing report...");
    }
}

Anonymous Classes — one-time implementation

Anonymous class implements an interface or extends a class inline, without a separate file.

Common with old event listeners; lambdas often replace them today.

Real-life example: A custom stamp order — one special design, no need to manufacture a whole stamp factory line.

Anonymous class
Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("Running anonymously");
    }
};
new Thread(task).start();