Search code examples
javainheritancepolymorphismcode-duplication

Inject functionality into two classes without common super class


I know what I wanna do sounds stupid but listen:

I have abstract classes Entity and Player (extends Entity) and non-abstract classes TestPlayer (extends Player) and TestMob (extends Entity).

Now I am facing the following problem:

I want to implement some abstract methods in Entity with the same functionality inside TestPlayer and TestMob. Theoretically I could just create another class TestEntity (extending Entity) and make TestPlayer and TestMob inherit from it. But then TestPlayer couldn't inherit from Player anymore.

Implementing the functionality directly inside Entity is not an option as it isn't intended for all sub-classes to have this functionality.

What could be considered an acceptable solution other than having duplicate code?


Solution

  • You could also use the Decorator Pattern (https://en.wikipedia.org/wiki/Decorator_pattern). You have a interface Entity and two classes implementing it: ConcreteEntity and Decorator, where ConcreteEntity has the default logic and Decorator has a reference to Entity and delegates all method invocations. Then you can extend Decorator. Instead of new TestPlayer(), you have new Player(new TestEntity(new ConcreteEntity)))