Unlock the complete
Logicmojo experience for FREE

1 Million +

Strong Tech Community

500 +

Questions to Practice

50 +

Jobs Referrals

Inheritance in OOPs

Back to home
Logicmojo - Updated Dec 11, 2023



Introduction

One of the most significant components of Object Oriented Programming is inheritance (OOP). The key to understanding Inheritance is that it provides code re-usability. In place of writing the same code, again and again, we can simply inherit the properties of one class into the other.

Inheritance is a technique of modelling real-world relationships, and OOP is all about real-world objects. Here's an example: a car, a bus, and a bicycle all fall under the umbrella term "vehicle." That is, they have inherited the attributes of the vehicle class, implying that they are all utilised for transportation.

We can represent this relationship in code with the help of inheritance.

An inherited class is called a subclass of its parent class or super class. The term "inheritance" is loosely used for both class-based and prototype-based programming, but in narrow use the term is reserved for class-based programming (one class inherits from another), with the corresponding technique in prototype-based programming being instead called delegation (one object delegates to another).

Interview Preparation Courses

• For Working Professionals Self-paced Course

Data Structures, Algorithms & System Design(HLD + LLD) in Java

Learn From Basic to Advanced DSA, Problem Solving, Scalable System Design (HLD + LLD),Design Patten etc

  • Curriculum

    Video Course

  • Duration

    Life Time Access

Course Fee : 4,000/-

• For Coding Interviews Self-paced Course

Data Structures, Algorithms & Problem Solving in Java

Learn From Basic to Advanced Data Structures, Algorithms & Problem-Solving techniques

  • Curriculum

    Video Course

  • Duration

    Life Time Access

Course Fee : 3,000/-





Terms Used in inheritance

  1. Class: A class is a collection of objects with similar attributes. It's a blueprint or template from which items are made.

  2. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.

  3. Super Class/Parent Class: The features of a subclass are inherited from the superclass. It's also known as a parent class or a base class.

  4. Reusability: Reusability, as the name implies, is a feature that allows you to reuse the fields and methods of an existing class while creating a new one. The fields and methods defined in the preceding class can be reused.







Types of Inheritance

Here are the different types of inheritance in Java:

Single Inheritance

In Single Inheritance one class extends another class (one class only).

In above diagram, Class B extends only Class A. Class A is a super class and Class B is a Sub-class.


Implementation in Java

import java.io.*;
import java.lang.*;
import java.util.*;

class A{
	public void printA()
	{
		System.out.println("Class-A");
	}
}

class B extends A{
	public void printB() 
	{ 
	    System.out.println("class-B"); 
	    
	}
}
public class Main {
	public static void main(String[] args)
	{
		B b = new B();
		b.printA();
		b.printB();
		b.printA();
	}
}


Multilevel Inheritance

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class.

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.


Implementation in Java

import java.io.*;
import java.lang.*;
import java.util.*;

class A {
	public void printA()
	{
		System.out.println("Class-A");
	}
}

class B extends A {
	public void printB() {
	    System.out.println("Class-B"); }
}

class C extends B {
	public void printC()
	{
		System.out.println("Class-C");
	}
}

public class Main {
	public static void main(String[] args)
	{
		C c=new C();
		c.printA();
		c.printB();
		c.printC();
	}
}


Hierarchical Inheritance

In Hierarchical Inheritance, one class is inherited by many sub classes.

As per above example, Class B, C, and D inherit the same class A.


Implementation in Java

class A {
	public void print_A() 
	{
	    System.out.println("Class A"); 
	    
	}
}

class B extends A {
	public void print_B() 
	{ 
	    System.out.println("Class B"); 
	    
	}
}

class C extends A {
	public void print_C() 
	{ 
	    System.out.println("Class C"); 
	    
	}
}

class D extends A {
	public void print_D() 
	{
	    System.out.println("Class D"); 
	    
	}
}


public class Test {
	public static void main(String[] args)
	{
		B obj_B = new B();
		obj_B.print_A();
		obj_B.print_B();

		C obj_C = new C();
		obj_C.print_A();
		obj_C.print_C();

		D obj_D = new D();
		obj_D.print_A();
		obj_D.print_D();
	}
}


Multiple Inheritance

Multiple Inheritance is one of the inheritance in Java types where one class extending more than one class. Java does not support multiple inheritance.

As per above diagram, Class C extends Class A and Class B both.

// Java program to illustrate the
// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

interface A {
	public void printLogic();
}

interface B {
	public void printMojo();
}

interface C extends A, B {
	public void printLogic();
}
class Child implements C {
	@Override 
	public void printLogic()
	{
		System.out.println("Logic");
	}

	public void printMojo() 
	{
	    System.out.println("Mojo"); 
	    
	}
}

public class Main {
	public static void main(String[] args)
	{
		Child c = new Child();
		c.printLogic();
		c.printMojo();
	}
}


Hybrid Inheritance

Hybrid inheritance is one of the inheritance types in Java which is a combination of Single and Multiple inheritance.

As per above example, all the public and protected members of Class A are inherited into Class D, first via Class B and secondly via Class C.

Note: Java doesn’t support hybrid/Multiple inheritence


Advantages of Inheritance

  1. Inheritance promotes reusability. When a class inherits or derives another class, it can access all the functionality of inherited class.

  2. Reusability enhanced reliability. The base class code will be already tested and debugged.

  3. As the existing code is reused, it leads to less development and maintenance costs.

  4. Inheritance makes the sub classes follow a standard interface.

  5. Inheritance helps to reduce code redundancy and supports code extensibility.

  6. Inheritance facilitates creation of class libraries.

Disadvantages of Inheritance

  1. Inherited functions work slower than normal function as there is indirection.

  2. Improper use of inheritance may lead to wrong solutions.

  3. Often, data members in the base class are left unused which may lead to memory wastage.

  4. Inheritance increases the coupling between base class and derived class. A change in base class will affect all the child classes.

With this article at Logicmojo, you must have the complete idea of inheritance in OOPs





Frequently Asked Questions (FAQs)



A key concept in object-oriented programming is inheritance, which allows a class to take on traits and characteristics from another class. It encourages class hierarchy and the reuse of existing code. Take the base class "Animal" as an illustration. It has characteristics like name and age, as well as a method called "eat()". Let's now make a "Dog" subclass that derives from the Animal class. The Dog class has the ability to add its own unique behaviors, such as the "bark()" method. The Dog class can expand or alter its own behavior while immediately gaining access to the Animal class's attributes and functions thanks to its inheritance from that class.



In object-oriented programming, a class can use inheritance as a mechanism to take on traits and characteristics from another class, referred to as the superclass or base class. It encourages the idea of hierarchical relationships between classes and allows for code reuse.

Three key ideas regarding inheritance:

• An "is-a" link between classes is established by inheritance, where a subclass is a customized version of its superclass.

• Because subclasses can inherit from and expand the functionality of their superclass, inheritance makes it easier to reuse code.

• The idea of polymorphism is supported by inheritance, which enables objects of various classes to be handled consistently based on their shared superclass



Inheritance benefits object-oriented programming:

Code reuse: Inheritance lets classes inherit properties and methods from their superclass, avoiding code duplication. Code reuse and redundancy are improved.

Modularity and extensibility: Inheritance hierarchically organizes classes for modular design. Extending classes to add or override functionality creates new classes. This improves codebase extensibility.

Polymorphism: Inheritance allows objects of different classes to behave equally based on their superclass. This versatility lets programs operate with varied things.



The "extends" or "inherits" keyword is typically used to describe inheritance in object-oriented programming languages.



Depending on how classes descended from one another, there are many types of inheritance. The typical inheritance patterns include:

Single inheritance: A class in this type only has one superclass from which to inherit. It creates a class hierarchy that is linear.

Multiple inheritance: A class may derive from more than one superclass through multiple inheritance. Due to the complexity and possibility for conflicts, not many programming languages enable this capability.

Multilevel inheritance: A subclass can become the superclass for another subclass in a process known as multilevel inheritance, resulting in a multilevel hierarchy.



In most Object-Oriented Programming (OOP) languages, the syntax for inheritance involves defining a child class and specifying the parent class it inherits from.

Here's a basic example in Python:

```python

class Parent:

pass

class Child(Parent):

pass

```

In this example, `Child` is the subclass that inherits from the `Parent` superclass. In Java or C++, the keyword `extends` or `:` is used respectively to establish the inheritance relationship. Note that the specific syntax may vary between programming languages.



Inheritance is a core principle of object-oriented programming where a class can inherit properties and behavior from another class. It promotes code reuse and hierarchical relationships among classes. For example, consider a base class called "Animal" with attributes like name and age, and a method called "eat()". Now, let's create a subclass called "Dog" that inherits from the Animal class. The Dog class can add its own specific behavior, like a method called "bark()". By inheriting from the Animal class, the Dog class automatically gains access to the attributes and methods of the Animal class, while being able to extend or customize its own behavior.



Inheritance in Python is a core concept of Object-Oriented Programming (OOP). It allows a class (child) to inherit attributes and methods from another class (parent). This promotes code reusability and logical structure. Child classes can override or extend the features inherited from parent classes. For instance, `class Parent: pass` defines a parent class, and `class Child(Parent): pass` defines a child class inheriting from Parent. The `super()` function can be used in a child class to call methods from the parent class. Python supports single, multiple, and multilevel inheritance.



Inheritance in C++ is a fundamental concept of Object-Oriented Programming (OOP). It allows one class to inherit the properties and methods of another class.



To encourage code reuse, lessen duplication, and organize code logically and hierarchically, inheritance is utilized. It makes the code easier to maintain and can save time by allowing child classes to inherit from and utilise the methods and properties of their parent classes.



The class being inherited from is a superclass, often known as a parent class. The class that derives from the superclass is referred to as a subclass or child class. The subclass may have its own particular properties and methods in addition to being able to use those defined by the superclass.



Classes that are intended to be subclassed but cannot be created on their own are known as abstract classes. They frequently have abstract methods (methods without a body) that all non-abstract child classes must implement. This makes it possible to specify a standard interface for subclasses..



Although inheritance is strong, if it is not used carefully, it can also cause issues. Increased complexity, close class coupling, difficulties modifying the superclass without affecting subclasses, and confusion resulting from "hidden" behaviors inherited from the superclass are a few of these.



It is possible for a subclass to propose a new implementation for a method that is already defined in its superclass thanks to the OOP feature of method overriding. When the behavior offered by the method of the superclass has to be changed in the subclass, this is utilized.


Logicmojo Learning Library