A data class can implement an interface and its abstract methods, or just inherit its default methods. The following is an example:
interface Organizer {} interface Speaker { abstract void conferenceTalk(); } abstract record Emp(String name, int age); record Manager(String name, int age, String country) extends Emp(name, age) // subclass a record implements Organizer; // implement one interface record Programmer(String name, int age, String programmingLang) extends Emp(name, age) // subclass a record implements Organizer, Speaker { // implementing multiple
// interfaces public void conferenceTalk() { // implement abstract
// method //.. code // from interface Speaker } };
The preceding code defines a tagging interface, Organizer (without any methods), and an interface, Speaker, with an abstract method, conferenceTalk(). We have two cases, as follows:
- A data class extending another data class, implementing an interface—the data class Manager extends the abstract Emp data class and implements the Organizer interface.
- A data class extending another data class and implementing multiple interfaces—the Programmer data class extends the abstract Emp data class and implements two interfaces—Organizer and Speaker. The Programmer data class must implement the abstract conferenceTalk() method from the Speaker interface to qualify as a non-abstract data class.
A data class can implement a single or multiple interfaces.