Java Record Implement Interface Example

1. Introduction

In this blog post, we'll explore how Java records can implement interfaces. Java records, introduced in Java 16, offer a concise syntax for creating immutable data classes. Integrating them with interfaces allows for combining the benefits of records with the flexibility of interface-driven design.

Definition

An interface in Java is a blueprint of a class. It has static constants and abstract methods. Java records can implement interfaces, allowing them to be used in a polymorphic way and adhere to specific contracts defined by the interfaces.

2. Program Steps

1. Define an interface with some methods.

2. Create a Java record that implements this interface.

3. Override the interface methods in the record.

4. Use the record in a context where the interface is expected.

3. Code Program

// Defining an interface
interface Printable {
    String print();
}

// Record implementing the Printable interface
public record Book(String title, String author) implements Printable {

    // Implementing the print method
    @Override
    public String print() {
        return "Book: " + title + " by " + author;
    }
}

public class Main {
    public static void main(String[] args) {
        Printable printable = new Book("1984", "George Orwell");

        // Using the overridden print method
        System.out.println(printable.print());
    }
}

Output:

Book: 1984 by George Orwell

Explanation:

1. The Printable interface defines a print method.

2. The Book record implements the Printable interface, thereby agreeing to provide an implementation of the print method.

3. In the Book record, the print method is overridden to return a formatted string representation of the book.

4. In the main method, a Book instance is created and referenced by the Printable interface type.

5. Calling printable.print() invokes the overridden method in Book, demonstrating how Java records can be used to implement and adhere to interface contracts.


Comments