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
Now, let's further customize the previous example by doing two things:
And that is it! We just implemented an interface using a Java record.
Rectangle
example, let's create an interface with the same two methods we used before.
public interface Shape {
double area();
double perimeter();
}
- Add
implements Shape
at the end of the record declaration (after the record constructor), and - Add
@Override
to the existing methods to ensure these methods comply with the contract established by theShape
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);
}
}
Comments
Post a Comment