Skip to main content
Composition vs Inheritance


Composition :
 Composition, simply mean using instance variables that are references to other objects. For example:

class A {
    //...
}
class B {
    private A objA = new A();
    //...
}

Composition is a "has-a" relation.
Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.


Two fundamental ways to relate classes are inheritance and composition. Although the compiler and Java virtual machine (JVM) will do a lot of work for you when you use inheritance, you can also get at the functionality of inheritance when you use composition.

 There are different views which favors COMPOSITION over Inheritance:

One example could be : java.util.Stack inherits java.util.Vector .
Stack is not a type of Vector, it should not be allowing random access, arbitrary insertion or deletion .
It could have been composition.

Another  favor for composition is : java does not support multiple inheritance . SO you can extend only one class.
But to achieve the multiple functionality , you can make object of multiple class as member of your class or you can use interfaces. But inheritance will not work in this case.
For example your class wants to display the lyrics and play the song.

You can easily unit test a class by making a Mock object of that.

In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implementation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object.
The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class.

The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class.

We can't change the implementations inherited from parent classes at run-time, because inheritance is defined at compile-time.
Object composition is defined dynamically at run-time through objects acquiring references to other objects.
But when you establish an inheritance relationship between two classes, you get to take advantage of dynamic binding and polymorphism. Dynamic binding means the JVM will decide at runtime which method implementation to invoke based on the class of the object.

* Back-end class object creation can be delayed(created when needed) in case of Composition.
But in case of Inheritance  you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.

It is easier to add new subclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism. If you have a bit of code that relies only on a superclass interface, that code can work with a new subclass without change. This is not true of composition, unless you use composition with interfaces. Used together, composition and interfaces make a very powerful design tool.

Comments

Popular posts from this blog

OBJECT class in Java

OBJECT class in Java : Object is at the top of class hierarchy in java. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class. Mainly below methods are provided by Object class : public String toString() returns the string representation of this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public boolean equals(Object obj) compares the given object to this object. public int hashCode() returns the hashcode number for this object. public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of ...

Java Priority Queue sort using lambda expression

Priority Queue :     In Java  Priority Queue  is a  queue  which keeps its elements sorted as per their natural order( example in ascending orders for Integer, alphabetical a-z for alphabets) or using a custom Comparator at the time of creation you can custom sort it. It has most method  similar to a queue  add, clear, poll, peek As priority queue have to compare elements to keep in order so elements must be comparable otherwise, it will throw ClassCastException .  As null can not be compared so you are not allowed to insert null too A program to sort priority queue using Lambda function in Java           c lass   PriorityQueueLambdaJava { public List<Integer> KFrequent( int [] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for ( int j: nums) { map .put(j, map .getOrDefault(j, 0 ) + 1 ); } PriorityQueue<Map.Entry<Integ...

Important Keywords: Static, Continue,Break:

Important Keywords: Static, Continue,Break:  Static: The static keyword in java is used for memory management mainly.  The static keyword members belongs to the class rather than instance of the class. Following members can be declared as static: variable (also known as class variable) method (also known as class method) block nested class  static variables : We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe . Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it as: ClassName.variableName //static variable example private static int a ge; public static String name; static methods: A static method belongs t...