Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Difference between Composition and Inheritance

Last Updated on April 12, 2023 by Prepbytes

The concept of reusable code in computer programming refers to the use of previously developed software in the creation of new software. Code reusability is recognized as an important component of productive functionality. Creating associations between classes is one-way object-oriented programming encourages this. There are two primary ways to construct these relationships in object-oriented programming: inheritance and composition. In object-oriented programming (OOP), inheritance refers to the process by which one or more objects can inherit the properties of another. It is one of the most powerful concepts in OOP for establishing code reuse. When using inheritance, a new class can be created by connecting parent-child relationships with pre-existing classes. This enables the development of new subtypes of existing classes.

What is Composition?

Composition is a design technique that allows a class to be composed of objects of other classes as its members. The objects provide the functionality needed by the class, and the class uses these objects to perform its tasks. Composition enables greater flexibility in code design, as it allows developers to build complex objects from smaller, simpler objects. It also allows for easy modification and replacement of individual objects, without affecting the entire class.

Code Implementation

class Engine {
    public void start() {
        System.out.println("Engine started.");
    }
}

class Car {
    private Engine engine;

    public Car() {
        this.engine = new Engine();
    }

    public void start() {
        this.engine.start();
        System.out.println("Car started.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.start();
    }
}

Output

Engine started.
Car started.

Explanation
In this example, we have two classes, Engine, and Car. The Engine class has a start() method that prints "Engine started." to the console. The Car class has a private instance variable engine of type Engine, which is initialized in the constructor. The Car class also has a start() method that calls the start() method of the engine object and then prints "Car started." to the console.

The Main class contains the main() method, which creates a new Car object and calls its start() method. When the program is run, the following output is produced: This example demonstrates composition in Java, where the Car class is composed of an Engine object. The Car class uses the Engine object to provide the functionality needed to start the car. By using composition, we have created a more modular and flexible design, as we can easily modify or replace the Engine object without affecting the Car class as a whole.

What is Inheritance?

Inheritance is a powerful tool for implementing code reuse in object-oriented programming. It is the functionality that allows one object to take on the characteristics of one or more other objects. In C++, inheritance means that you can create classes that inherit attributes from other classes. This implies that you specialize a class in order to establish an is-a relationship between the classes, resulting in a strong coupling between the base and derived classes. Because new classes are created from existing classes, inheritance promotes code reusability. Class inheritance also makes it easier to modify the reused implementation. However, there are some disadvantages to class inheritance.

It is a property that enables a class to inherit properties and methods from a parent class. Inheritance allows developers to create new classes that are based on existing classes, thereby promoting code reuse and reducing duplication. Inheritance provides a more structured approach to code design, as it creates a hierarchy of classes where each subclass inherits properties and methods from its parent class.

Code Implementation

 class Animal {
    public void speak() {
        System.out.println("Animal speaks.");
    }
}

class Dog extends Animal {
    public void speak() {
        System.out.println("Dog barks.");
    }
}

 class Cat extends Animal {
    public void speak() {
        System.out.println("Cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.speak();

        Dog dog = new Dog();
        dog.speak();

        Cat cat = new Cat();
        cat.speak();
    }
}

Output

Animal speaks.
Dog barks.
Cat meows.

Explanation
In this example, we have an Animal class with a speak() method that prints "Animal speaks." to the console. We also have two subclasses, Dog and Cat, which extend the Animal class and override the speak() method to print "Dog barks." and "Cat meows." to the console, respectively.

When we create objects of each class and call their speak() method in the main() method, the following output is producedThis example demonstrates how inheritance enables us to create subclasses that share properties and methods with their parent class but can also add new properties and methods of their own. In this case, both the Dog and Cat classes inherit the speak() method from the Animal class but also add their unique behavior.

Difference between Composition and Inheritance

Here we have the difference between composition and inheritance

        Composition               Inheritance
Composition is a has-a relationship Inheritance represents  the is-a relationship
We can achieve multiple inheritance using composition Java doesn’t allow multiple inheritance
Composition does not create a hierarchy of classes It creates a hierarchy of class
Composition does not allow direct access to the members of the composed objects A child class can access all public and protected members of the parent class
The composition can be more flexible and allows objects to be reused in different contexts Inheritance creates a tight coupling between the parent and child classes
Changes to the composed objects do not affect other composed objects Changes to the parent class can affect all child classes
Composition allows code reuse even from final classes. Inheritance cannot extend the final class

Conclusion
In conclusion, we can say the main difference between composition and inheritance is that in composition, objects of different classes are combined to create a more complex object, while in inheritance, a new class is created from an existing class by inheriting its properties and behaviors. Composition involves a "has-a" relationship between objects, while inheritance involves an "is-a" relationship between classes. Composition is more flexible and allows objects to be reused in different contexts, while inheritance promotes code reuse and can simplify code by reducing duplication.

Frequently Asked Question

Here we have FAQs on the difference between composition and inheritance

Q1: When should I use composition and when should I use inheritance?
Ans: Composition should be used when you need to create complex objects from simpler ones, or when you want to create objects that can be easily reused in different contexts. Inheritance should be used when you need to create a new class that is a modified version of an existing class, or when you want to create a class hierarchy that reflects the relationship between different types of objects.

Q2: What are the advantages of composition over inheritance?
Ans: One advantage of composition is that it allows for greater flexibility and modularity, as components can be easily swapped out or modified without affecting the containing object. The composition also avoids the problem of inheritance hierarchies becoming too complex and difficult to manage. Additionally, the composition can allow for more fine-grained control over the behavior of an object, as each component can be tailored to a specific task or responsibility.

Q3: What are the advantages of inheritance over composition?
Ans: One advantage of inheritance is that it can make code more concise and easier to read, as properties and methods can be inherited from the superclass rather than being explicitly defined in the subclass. Inheritance can also simplify the design of a system by reflecting the natural hierarchy of objects. Finally, inheritance can help to reduce code duplication, as common functionality can be defined in the superclass and reused by all subclasses.

Leave a Reply

Your email address will not be published. Required fields are marked *