I started wondering whether or not there are any situations where inheritance cannot be replaced by composition?
Take for example a simple inheritance with overloading:
class Foo {
String getText() {
return "Text from foo";
}
}
class Bar extends Foo {
@Override
String getText() {
return "BAR> " + super.getText() + " <BAR";
}
}
This can be replaced with composition like this:
class Bar {
Foo foo;
String getText() {
return "BAR> " + foo.getText() + " <BAR";
}
}
...resulting in exact same result. If both Foo
and Bar
implement the same interface, it becomes even more obvious that the two snippets above equal to same behavior.
So, back to the original question: are there any situations where one must (or really, really should) use inheritance instead of composition?