How do I implement an interface in Java?

An interface defines a contract that implementing classes must follow. You can use it to describe a behavior without choosing a specific implementation.

In this example, you will create a Printable interface and implement it in a Book class.

Source code

Save the following code as InterfaceExample.java:

public class InterfaceExample {
    void main() {
        Printable item = new Book("Learning Java", "Alice");

        item.printDetails();
    }
}

interface Printable {
    void printDetails();
}

class Book implements Printable {
    private final String title;
    private final String author;

    Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    @Override
    public void printDetails() {
        IO.println("Title: " + title);
        IO.println("Author: " + author);
    }
}

Explanation

The Printable interface declares a method:

interface Printable {
    void printDetails();
}

This declaration specifies the method’s name, parameters, and return type. It does not provide a method body.

The method is implicitly public and abstract, so you do not need to write those modifiers here.

Implementing the interface

The Book class uses the implements keyword:

class Book implements Printable {

Because Book is a concrete class, it must provide an implementation of the interface’s abstract method:

@Override
public void printDetails() {
    IO.println("Title: " + title);
    IO.println("Author: " + author);
}

The implementation must be public. Giving it more restrictive access would cause a compilation error.

The @Override annotation lets the compiler check that this method implements an inherited method correctly.

Using an interface as a variable type

The following statement creates a Book object and assigns its reference to a variable of type Printable:

Printable item = new Book("Learning Java", "Alice");

This is valid because Book implements Printable.

The calling code can then use the method declared by the interface:

item.printDetails();

At runtime, Java executes the implementation in Book.

Using an interface as the variable type lets the calling code work with any implementation of that interface.

Run the example

Compile and run the file:

javac InterfaceExample.java
java InterfaceExample

Output

Title: Learning Java
Author: Alice

A class can implement multiple interfaces. Use interfaces when different classes should provide the same behavior, even if those classes do not share a custom superclass.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.