Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of composition over inheritance in Java

Tags:

java

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

like image 222
dr_dev Avatar asked Dec 02 '22 12:12

dr_dev


1 Answers

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>();
        }
    }
}
like image 55
Eran Avatar answered Dec 05 '22 07:12

Eran