Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: inheritance

What are some alternatives to inheritance?

like image 267
Registered User Avatar asked May 19 '26 12:05

Registered User


2 Answers

Effective Java: Favor composition over inheritance. (This actually comes from Gang of Four, as well).

The case he makes is that inheritance can cause a lot of unseemly side effects, if the extended class was not explicitly designed to be inherited. For example, any calls to super.someMethod() can lead you through unexpected paths of unknown code.

Instead, hold a reference to the class you would have otherwise extended, and delegate to it.

Here is a link to an interview with Erich Gamma where he talks about the concept a bit.

like image 180
danben Avatar answered May 21 '26 00:05

danben


Some alternatives:

  • Delegation, also known as Composition
  • Wikipedia article on limitations and alternatives to inheritance
  • Q:Inheritance seems error-prone. How can I guard against these errors? And, what are the alternatives?
like image 26
Paul Wagland Avatar answered May 21 '26 02:05

Paul Wagland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!