Posts

Showing posts from August, 2011

Why is composition harder than inheritance?

(just some random thoughts...) Let's take this Java example: class Base { public void method() {} } class Derived extends Base {} See how easy it is for Derived to "reuse" code from Base ? Derived is a subclass of Base , and in its constructor it calls Base 's constructor, constructing a Base before constructing a Derived : class Derived extends Base { // this is what gets generated by the compiler: public Derived() { super(); } // this doesn't exist, but illustrates what happens when we call Derived.method: public void method() { super.method(); } } Also, Derived instances have a "forwarding" method, that, when called, will delegate to the corresponding base method (this is not technically what happens, but I'm looking at the "concept" here). Isn't that convenient? Why isn't the same capability available to compose classes? Composition is always a better strategy than inheritance in "reuse" ...