Open In App

Difference between Inheritance and Composition in Java

Last Updated : 22 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Inheritance: 
When we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. In doing this, we can reuse the fields and methods of the existing class without having to write them ourself.

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Types of Inheritance are: 

  1. Single inheritance
  2. Multi-level inheritance
  3. Multiple inheritances
  4. Hybrid inheritance
  5. Hierarchical inheritance

Example of Inheritance: 

Java




class A {
    int a, b;
    public void add(int x, int y)
    {
        a = x;
        b = y;
        System.out.println(
            "addition of a + b is:"
            + (a + b));
    }
}
 
class B extends A {
    public void sum(int x, int y)
    {
        add(x, y);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        B b1 = new B();
        b1.sum(5, 6);
    }
}


Output: 

addition of a+b is:11 

Here, class B is the derived class which inherit the property(add method) of the base class A.

Composition: 
The composition also provides code reusability but the difference here is we do not extend the class for this.

Example of Composition: 
Let us take an example of the Library

Java




// Java program to illustrate
// the concept of Composition
 
import java.io.*;
import java.util.*;
 
// class book
class Book {
 
    public String title;
    public String author;
 
    Book(String title, String author)
    {
 
        this.title = title;
        this.author = author;
    }
}
 
// Library class contains
// list of books.
class Library {
 
    // reference to refer to the list of books.
    private final List<Book> books;
 
    Library(List<Book> books)
    {
        this.books = books;
    }
 
    public List<Book> getTotalBooksInLibrary()
    {
 
        return books;
    }
}
 
// main method
class GFG {
    public static void main(String[] args)
    {
 
        // Creating the Objects of Book class.
        Book b1 = new Book(
            "EffectiveJ Java",
            "Joshua Bloch");
        Book b2 = new Book(
            "Thinking in Java",
            "Bruce Eckel");
        Book b3 = new Book(
            "Java: The Complete Reference",
            "Herbert Schildt");
 
        // Creating the list which contains the
        // no. of books.
        List<Book> books = new ArrayList<Book>();
        books.add(b1);
        books.add(b2);
        books.add(b3);
 
        Library library = new Library(books);
 
        List<Book> bks = library.getTotalBooksInLibrary();
        for (Book bk : bks) {
 
            System.out.println("Title : "
                               + bk.title + " and "
                               + " Author : "
                               + bk.author);
        }
    }
}


Output:

Title : EffectiveJ Java and  Author : Joshua Bloch
Title : Thinking in Java and  Author : Bruce Eckel
Title : Java: The Complete Reference and  Author : Herbert Schildt

Difference between Inheritance and Composition:

S.NO Inheritance Composition
1. In inheritance, we define the class which we are inheriting(super class) and most importantly it cannot be changed at runtime Whereas in composition we only define a type which we want to use and which can hold its different implementation also it can change at runtime. Hence, Composition is much more flexible than Inheritance.
2. Here we can only extend one class, in other words more than one class can’t be extended as java do not support multiple inheritance. 
 
Whereas composition allows to use functionality from different class.
3. In inheritance we need parent class in order to test child class. Composition allows to test the implementation of the classes we are using independent of parent or child class.
4. Inheritance cannot extend final class. Whereas composition allows code reuse even from final classes.
5. It is an is-a relationship. While it is a has-a relationship.

 



Similar Reads

Favoring Composition Over Inheritance In Java With Examples
Favoring Composition over Inheritance is a principle in object-oriented programming (OOP). Classes should achieve polymorphic behavior and code reuse by their composition rather than inheritance from a base or parent class. To get the higher design flexibility, the design principle says that composition should be favored over inheritance. Inheritan
4 min read
Difference Between Aggregation and Composition in Java
Aggregation and composition describe the type of relationships between objects when communicating with each other, this might be used in low-level design to depict associations between objects. In this article, we are going to discuss the differences between Aggregation and Composition in Java programming language. Aggregation It is a special form
7 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In this article, we will understand the difference
3 min read
Association, Composition and Aggregation in Java
Association is a relation between two separate classes which is established through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to another object to use functionality and services provided by that object. Composition and Aggregation are the two forms of
9 min read
Composition in Java
The composition is a design technique in java to implement a has-a relationship. Java Inheritance is used for code reuse purposes and the same we can do by using composition. The composition is achieved by using an instance variable that refers to other objects. If an object contains the other object and the contained object cannot exist without th
4 min read
Difference between Containership and Inheritance in C++
Containership: When an object of one class is created into another class then that object will be a member of that class, this type of relationship between the classes is known as containership or has_a relationship as one class contains the object of another class. The class which contains the object and members of another class in this kind of re
4 min read
Java and Multiple Inheritance
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which
6 min read
Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in Method Area. For each .class file, JVM will store corresponding information in Method Area. Now incorporating inheritance in class loading. In java inheritance, JVM will first load and initialize the parent class and then it loads and initialize the child class. Example
3 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interf
7 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes
3 min read
Practice Tags :