4 ms·
So I should never use the AbstractList, AbstractSet, AbstractMap, or AbstractCollection Java classes for implementing their relative data structures? Instead of
by sreque 16y ago
So I should never use the AbstractList, AbstractSet, AbstractMap, or AbstractCollection Java classes for implementing their relative data structures? Instead of reusing the code these classes provide through inheritance, I should instead be using composition?
Code reuse is the only good reason to use concrete inheritance and there are many situations where concrete inheritance is much cleaner than composition. Honestly, this whole conversation feels a little silly to me.
- jknupp 16y agoImplementing an abstract class when the concrete implementation conforms to the Liskov Substitution Principle is exactly when inheritance does make sense. You would do this so that calling code wouldn't need to care that the function required a MySpecialMapClass rather then something that conforms to the AbstractMap interface. However, if you just think that some of the functions in AbstractMap are useful but plan on creating a totally different class that doesn't conform to the interface, then inheritance is inappropriate. Code reuse is not a reason to use inheritance; it is a byproduct of it.
- ipreuss 16y agoI think you need to distinguish between interface inheritance and implementation inheritance. The reason to use interface inheritance is to allow polymorphism in a statically typed language. The only reason to use implementation inheritance is code reuse. And yes, you should only do that if the classes conform to the LSP.