I have two interfaces, HasClickHandlers
and DoesFancyFeedback
. Then I have some UI objects that implement both interfaces - for example, a Button
that implements both has click handlers and also does fancy feedback.
In my code that's declaring Button
s, I don't want to actually say Button
because maybe later I'll want it to be, I don't know. An Image
that has click handlers and does fancy feedback. So instead of being specific and saying something like:
Button saveButton = aButtonIPassedIn;
saveButton.addClickHandler();
saveButton.doFancyFeedback();
I want to say,
{HasClickHandlers + DoesFancyFeedback} clickyFeedbackThing = aThingIPassedIn;
clickyFeedbackThing.addClickHandler();
clickyFeedbackThing.doFancyFeedback();
I want the compiler to require that aThingIPassedIn
implement both HasClickHandlers
and DoesFancyFeedback
.
I could create an interface that extends those two interfaces, and use that. Is there any easier/less verbose way?
Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface. An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements.
An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.
Extending Multiple InterfacesMultiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
No need for a third interface nor additional method.
Optional.ofNullable((HasClickHandlers & DoesFancyFeedback)clickyFeedbackThing).ifPresent(then -> {
then.addClickHandler();
then.doFancyFeedback();
});
I do not think that there is a better way to do what you want. I just wanted to suggest you to do the following. You can create method (let's call it foo) that accepts argument that requires 2 interfaces:
<T extends HasClickHandlers & DoesFancyFeedback> void foo(T arg);
Please pay attention on one ampersand between 2 your interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With