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.