The below paragraph is quoted from the book, "Thinking in Java" by Bruce Eckel.
Composition comes with a great deal of flexibility. The member objects of your new class are typically private, making them inaccessible to the client programmers who are using the class. This allows you to change those members without disturbing existing client code. You can also change the member objects at run time, to dynamically change the behavior of your program. Inheritance, which is described next, does not have this flexibility since the compiler must place compile-time restrictions on classes created with inheritance.
I don't understand, how the member object can be changed dynamically, and how it is an advantage over inheritance. Could somebody please explain this
If your class extends ArrayList
, a user of your class has access to all the public methods of ArrayList
. You can't change your class to extend LinkedList, since that may break existing code.
public class Inheritence extends ArrayList<String>
{
// here your class depends on ArrayList implementation
}
If, on the other hand, your class has a private member whose type is List
, the users of your class can't call methods of that member directly. And you can decide in runtime whether to assign an ArrayList
instance to that member, or assign a different List
implementation (LinkedList
or something else).
public class Composition
{
private List<String> member;
public Composition ()
{
// here you decide the type of your member during runtime
if (someCondition) {
member = new ArrayList<String>();
} else {
member = new LinkedList<String>();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With