Implementing Interfaces with Java Records

If you have not read my article on Java records and do not know about this topic, please read my blog titled "Customizing Java Records" first and then come back to this one.

Now that you know how to customize Java records, implementing an interface using Java records should be very easy to understand. If you don't know about interfaces in Java, you can read more on my article about interfaces. The recipe for implementing an interface is simply an expansion of what you learned in my previous blog on how to customize a Java record. Following our Rectangle example, let's create an interface with the same two methods we used before.


public interface Shape {
    double area();
    double perimeter();
}
Now, let's further customize the previous example by doing two things:
  1. Add implements Shape at the end of the record declaration (after the record constructor), and
  2. Add @Override to the existing methods to ensure these methods comply with the contract established by the Shape interface

public record Rectangle (double width, double height) implements Shape {

    @Override
    public double area() {
        return width * height;
    }

    @Override
    public double perimeter() {
        return 2 * (width + height);
    }
}
And that is it! We just implemented an interface using a Java record.

Comments

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

Exception Handling: File CRUD Operations Example

The Beauty of the Null Object Pattern