Good reasons to prohibit inheritance in Java?

cretzel picture cretzel · Oct 20, 2008 · Viewed 61.1k times · Source

What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?

Answer

DJClayworth picture DJClayworth · Oct 20, 2008

Your best reference here is Item 19 of Joshua Bloch's excellent book "Effective Java", called "Design and document for inheritance or else prohibit it". (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize.

The interaction of inherited classes with their parents can be surprising and unpredicatable if the ancestor wasn't designed to be inherited from.

Classes should therefore come in two kinds :

  1. Classes designed to be extended