0

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?

Michael
  • 41,989
  • 11
  • 82
  • 128
manabreak
  • 5,415
  • 7
  • 39
  • 96
  • It doesn't make sense to label a question as both 'java' and 'language-agnostic': fixed. – Stephen C May 20 '19 at 08:59
  • 3
    Possible duplicate of [Can inheritance be replaced completely by composition?](https://stackoverflow.com/questions/15749316/can-inheritance-be-replaced-completely-by-composition) – Michael May 20 '19 at 09:00

2 Answers2

0

are there any situations where one must (or really, really should) use inheritance instead of composition?

When some behavior is abstract it makes more sense to express it with inheritance as trying to express it with composition which could look unnatural/confusing.

Spotted
  • 4,021
  • 17
  • 33
0

whether or not there are any situations where inheritance cannot be replaced by composition?

No! But consider:

whether or not there are any situations where inheritance should not be replaced by composition?

Yes! Imagine your Foo class has 10 methods. Using composition you have to rewrite those 10 methods in Bar. The code might be simple since it delegates most of the tasks to Foo but it is still quite frustrating.

I won't talk about what people call "Is A" or "Has A" as it doesn't make sense to me. Personally I consider inheritance/composition is all about code reuse. What makes you reuse code easier in your situation, use it. Inheritance in programming is not about taxonomy, I usually found analogies like Animal/Dog/Cat ... not helpful.

Nghia Bui
  • 3,694
  • 14
  • 21