Search code examples
javadata-structureslinked-listdoubly-linked-list

Creating doubly linked list(DLL) from a basic linked list-Composition or inheritance?


Say my BasicLinkedList(BLL) has these following basic methods:

-insert at the head, tail, anywhere
-delete at the head, tail, anywhere

I want to know if I should use composition or inheritance to create my DLL from BLL.

My thought process:

My guess was composition from the read up of Effective Java Item #18(3rd Edition): Favour composition over inheritance.

But composition didn't feel right here as I didn't know how to incorporate the pointer to previous node with delegation.

Then I read up on Liskov substitution Principle(LSP) and seems that inheritance is the right choice? But I'm not sure.


Question(summarised): Should I use composition or inheritance to create my DLL from BLL? Why?


Solution

  • "Favor composition over inheritance" does not mean you should never use Inheritance and that Inheritance is always bad. In this particular case, you are better off using inheritance to gain access to the necessary class variables and methods.