Java – Why avoid Java Inheritance “Extends”

designdesign-patternsjavaobject-oriented-design

Jame Gosling said

“You should avoid implementation inheritance whenever possible.”

and instead, use interface inheritance.

But why? How can we avoid inheriting the structure of an object using the keyword "extends", and at the same time make our code Object Oriented?

Could someone please give an Object Oriented example illustrating this concept in a scenario like "ordering a book in a bookstore?"

Best Answer

Gosling did not say to avoid the use of extends keyword... he just said to not use inheritance as a means to achieve code re-use.

Inheritance is not bad per se and is a very powerful (essential) tool to use in creating OO structures. However when not used properly (that is when used for something else than creating Object structures) it creates code that is very tightly coupled and very hard to maintain.

Because inheritance should be used for creating polymorphic structures it can be done just as easily with interfaces, hence the statement to use interfaces rather than classes when designing your Object Structures. If you find yourself using extends as a means to avoid copy-pasting code from one object to another perhaps you are using it wrong and would be better served with a specialized class to handle this functionality and share that code through composition instead.

Read about the Liskov Substitution Principle and understand it. Whenever you are about to extend a class ( or an interface for that matter) ask yourself if you are violating the principle, if yes then you are most likely (ab)using inheritance in unnatural ways. It is easy to do and often seems like the right thing but it will make your code more difficult to maintain, test and evolve.

--- Edit This answer makes a pretty good argument to answer the question in more general terms.