Comparison
DelegationvsInheritance
Delegation
the method body is one line that calls the same method on a field, and that is the whole class's job for that method.
Holding another object and forwarding work to it, exposing only what you choose to expose. It is what composition looks like at the method level, and it is the mechanism behind every wrapper pattern in the structural cluster. It costs boilerplate — one forwarding method per operation, which is why languages that generate delegation automatically make composition noticeably more attractive.
Full entry →Inheritance
you got twenty methods you never asked for along with the one you wanted, and you cannot give any of them back.
Deriving a class from another so it acquires the parent's fields and methods and may replace some of them. It is the strongest coupling one class can have to another: the subclass depends not just on the parent's public surface but on which of its own methods the parent calls internally. That is why it is the default in textbooks and increasingly the second choice in practice.
Full entry →