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
XData
to hold the fields the interface needs to work with, and a public interfaceX
in the sameX.java
source file - The interface has one virtual method
getXData()
that returns theXData
instance - 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
Y
and classYData
in the same pattern - Create a class
XY
that implements both interfacesX
andY
- The class
XY
hasXData
andYData
fields, which are returned bygetXData()
andgetYData()
. These are the only two interface methodsXY
is required to implement. - I didn't bother in my example, but
XY
would have to decide how to implement the Object methodshashCode
,equals
, andtoString
. These methods cannot be implemented by interfaces (but they could be implemented inXData
andYData
classes 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