Ever since Java 8 introduced default interface methods, I felt there had to be a way to use it for multiple inheritance. I have never needed it, but I was bored for a bit today, so decided to try the following idea:
- Create a non-public class
XDatato hold the fields the interface needs to work with, and a public interfaceXin the sameX.javasource file - The interface has one virtual method
getXData()that returns theXDatainstance - The remaining interface methods are default methods that call
getXData()to read and write the fields as necessary to perform some useful operations. - Create another interface
Yand classYDatain the same pattern - Create a class
XYthat implements both interfacesXandY - The class
XYhasXDataandYDatafields, which are returned bygetXData()andgetYData(). These are the only two interface methodsXYis required to implement. - I didn't bother in my example, but
XYwould have to decide how to implement the Object methodshashCode,equals, andtoString. These methods cannot be implemented by interfaces (but they could be implemented inXDataandYDataclasses if desired)
The end result is the XY class is an instance of both X and Y interfaces, and inherits the encapsulated behaviors of both X and Y default methods - multiple inheritance by any reasonable measure.
from DZone.com Feed https://ift.tt/x5RE0Km
No comments:
Post a Comment