1

I can't wrap my head around this statement here:

One common drawback of using composition instead of inheritance is that methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods

What does it mean?

3

When you use inheritance, the class Derived will inherit the methods of the Base class. You can use them as they are. You'll override inherited methods only if you need a different behavior, or if the base method is abstract.

public class Base {
   public void presentYourself() { ... }
}
public class Derived extends Base {
}
...
    Derived d = ...; 
    d.presentYourself();    // <<---- works out of the box 

In the composition, especially if you use composition over inheritance, you expose in a Composite the methods offered by its Component. In absence of inheritance, you will need to implement all the relevant methods of Component's interface in Composite. This means that even if you provide exactly the same method than in Component and there is no specific behavor, you'll nevertheless need to implement at least a method that calls the method of the composed Component object.

public class Component {
   public void presentYourself() { ... }
}
public class Composite {
   private Component c;  
   public void presentYourself() { c.presentYourself(); } //<- FORWARDING
   ...
}
...
    Composite x = ...; 
    x.presentYourself();    // Works only if explicitly implemented

In other words, this means that with composition you might have a lot of boilerplate code that just calls a methods of another object, with the same parameters.

2

It means that, if you're using inheritance, you get the use of the base class's methods for free, whereas if you're using composition, it sometimes takes a little more work to wire up the necessary methods in the classes you're composing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.