SyntaxStudy
Sign Up
Java Defining and Implementing Interfaces
Java Beginner 1 min read

Defining and Implementing Interfaces

An interface in Java is a reference type that defines a contract of methods a class must implement. Interfaces contain only abstract methods (before Java 8), constants, and type declarations. A class implements an interface using the implements keyword and must provide an implementation for every abstract method in the interface, or be declared abstract itself. Interfaces enable a powerful form of abstraction called programming to an interface: you write code that works with an interface type rather than a concrete class. Any class that implements the interface can be used wherever the interface type is expected. This decouples the calling code from the implementation details and makes it easy to swap implementations. An interface can extend another interface (or multiple interfaces) using extends. A class can implement multiple interfaces, which is how Java achieves a form of multiple inheritance without the diamond problem of state. Interface constants are implicitly public static final; interface methods are implicitly public abstract (for traditional abstract methods).
Example
import java.util.List;

// Interface defining a contract
interface Printable {
    void print();                            // implicitly public abstract
}

interface Saveable {
    boolean save(String destination);
}

// Interface extending multiple interfaces
interface Document extends Printable, Saveable {
    String getTitle();
    int    getPageCount();
}

// Concrete implementation
class PdfDocument implements Document {
    private final String title;
    private final List<String> pages;

    PdfDocument(String title, List<String> pages) {
        this.title = title;
        this.pages = pages;
    }

    @Override public String getTitle()     { return title; }
    @Override public int    getPageCount() { return pages.size(); }

    @Override public void print() {
        System.out.println("=== PDF: " + title + " ===");
        for (int i = 0; i < pages.size(); i++) {
            System.out.printf("Page %d: %s%n", i + 1, pages.get(i));
        }
    }

    @Override public boolean save(String destination) {
        System.out.printf("Saving '%s' to %s%n", title, destination);
        return true;  // success
    }
}

public class InterfaceDemo {

    // Programming to the interface — works for any Document implementation
    static void processDocument(Document doc) {
        System.out.println("Processing: " + doc.getTitle()
            + " (" + doc.getPageCount() + " pages)");
        doc.print();
        doc.save("/tmp/" + doc.getTitle().replaceAll("\\s+", "_") + ".pdf");
    }

    public static void main(String[] args) {
        PdfDocument doc = new PdfDocument(
            "Java Guide",
            List.of("Introduction to Java", "Data Types", "Control Flow")
        );
        processDocument(doc);
    }
}