Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid multiple inheritance?

For a project, I have following classes:

  • SuperClass
  • Subclass 1
  • Subclass 2

The two subclasses extend the superclass. Now, I need a third class with the EXACT behaviour (read, same overriden method implementations) of both SubClass 1 and Subclass 2. Because Subclass 1 overrides only 1 method in SuperClass, and Subclass 2 doesn't override that method, I want to make the third class inherit Superclass and just implement it with the methods of Subclass 1 and Subclass 2. Now, is this good OO-design? I see no other solution because multiple inheritance in Java just isn't possible. Are there any alternatives?

like image 238
Programmer1994 Avatar asked Dec 07 '22 21:12

Programmer1994


1 Answers

Java8 introduced default and static methods for interfaces. To a certain degree, that allows for multiple inheritance. But most likely, the correct solution would be to rework your design.

You see, inheritance is not about code re-use. It is about creating useful abstractions; and make good use of polymorphism for example.

In your case: maybe those functionalities could/should be put into smaller interfaces; and then segregated into their own, independent classes. And then you use composition of objects instead of inheritance to build the thing you need.

like image 158
GhostCat Avatar answered Dec 27 '22 02:12

GhostCat