In: Computer Science
Explain why composition is generally preferred to inheritance for achieving code reuse.
Before talking about the inclination of Composition over Inheritance for accomplishing code reusability, let me give you a brief idea about Composition and Inheritance.
Composition have "HAS-A" relationship. During this an object owns another objects instead of just use that object. It basically means if the main object are going to be destroyed all the interior objects owned by main object should be destroyed also. Example: during this example, class BMW is said to class Car by composition, because BMW has an instance variable that holds a regard to a Car object.
class Car {
//...
}
class BMW {
public Car car1 = new Car();
//...
}
Inheritance have "IS-A" relationship. it's used for establishing the relationship between different classes. Subclass may inherit the properities and methods of its superclass. Superclass have rights to override some methods and properities to switch the default behaviour of parent class. Example: during this simple example, class BMW is associated with class Car by inheritance, because BMW extends Car. during this example, Car is the superclass and BMW is the subclass.
class Car { //... } class Car extends BMW { //... }
The reasons are as follows: