0

Java does not allow multiple superclasses; and interfaces cannot have method bodies as I know. So how to handle the case in which I want to inherit two implemented methods of different superclasses.

Suppose that I create classes for objects which can do some specific tasks, let's say objects can play and sing. Some objects only play and their subclasses as well, so there is no need to define the exact same play() method for each subclass, I define it in superclass Player. Some objects only sing, so, I define the generic sing() method in superclass Singer, not in each subclass. What to do, if a subclass can sing and play, so need to extend Player and Singer superclasses to be able to apply implemented play() and sing() methods of superclasses. How to handle that kind of situation, in the best efficient way?

1 Answers1

1

Starting with Java 8 interfaces can have default methods. These methods are marked with the default keyword and can have an implementation in the interface, that can then be used in (or reimplemented by) classes implementing the interface. Classes can also implement multiple interfaces, so you could have a class implement both Player and Singer and provide default methods play() and sing() in their respective interfaces. This is also useful if you want to modify an interface without having to also modify the classes that already implement it.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24