Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Inheritance in Java?
2.1.
Why do we need inheritance in Java?
3.
Benefits of Inheritance in Java
4.
How to use Inheritance in Java
5.
Types of Inheritance in Java
5.1.
Single Inheritance 
5.2.
MultiLevel Inheritance
5.3.
Hierarchical Inheritance
5.4.
Multiple Inheritance
5.5.
Hybrid Inheritance
6.
Inheritance with an Example
6.1.
Java
7.
Overwrite Functions
8.
​​Advantages of Inheritance in Java:
9.
​​Disadvantages of Inheritance in Java:
10.
Frequently Asked Questions
10.1.
Where is inheritance used in Java? 
10.2.
Is Multiple Inheritance in Java supported?
10.3.
What is the real-life application of inheritance in Java?
11.
Conclusion
Last Updated: May 5, 2024
Easy

Inheritance In Java

Author Raksha Jain
1 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Inheritance lies at the heart of object-oriented programming (OOP) paradigms, empowering developers to build robust and extensible software systems. In Java, a language renowned for its OOP capabilities, understanding inheritance is essential for mastering its vast ecosystem of libraries and frameworks. 

Inheritance in Java

In this blog, we'll delve into the intricacies of inheritance in Java, exploring its principles, syntax, and practical applications.

Recommended topic Iteration Statements in Java and Hashcode Method in Java

What is Inheritance in Java?

In Java, inheritance is a fundamental feature of object-oriented programming that allows a class (subclass or derived class) to inherit properties and behaviors (methods and fields) from another class (superclass or base class). This enables code reuse and promotes a hierarchical structure among classes, facilitating better organization and maintenance of code.

Why do we need inheritance in Java?

Here are some reasons why inheritance is crucial in Java:

  • Code Reusability: Inheritance allows subclasses to inherit fields and methods from their superclass, reducing code duplication and promoting reuse of existing code.
  • Hierarchy and Organization: Inheritance enables the creation of hierarchical relationships among classes, reflecting real-world relationships and improving code organization.
  • Polymorphism: Through inheritance, Java supports polymorphism, allowing objects of different subclasses to be treated interchangeably through their common superclass interface.
  • Extension and Specialization: Subclasses can extend and specialize the functionality of their superclass, adding new features or modifying existing ones without altering the superclass itself.
  • Maintenance and Updates: Changes made to the superclass automatically propagate to its subclasses, ensuring consistency and reducing the effort required for maintenance and updates.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Benefits of Inheritance in Java

  • Code Reuse: Inheritance promotes reuse of existing code, reducing redundancy and improving efficiency.
  • Flexibility: It allows for the creation of flexible and modular code structures, facilitating easy adaptation to changing requirements.
  • Readability and Understandability: Inheritance enhances code readability by promoting a hierarchical organization that mirrors real-world relationships.
  • Polymorphism: Inheritance enables polymorphic behavior, allowing for dynamic method dispatch and enhancing code flexibility and extensibility.
  • Efficient Development: By leveraging existing classes and hierarchies, inheritance accelerates the development process and encourages modular design.

How to use Inheritance in Java

  • Syntax: Use the extends keyword to establish an inheritance relationship between classes.
  • Superclass and Subclass: Define a superclass with common properties and behaviors, then create subclasses that inherit from the superclass.
  • Access Modifiers: Utilize access modifiers like public, protected, and private to control the visibility of inherited members.
  • Constructor Chaining: Use super() to call the constructor of the superclass from a subclass constructor, ensuring proper initialization of inherited members.
  • Override Methods: Subclasses can override methods inherited from the superclass to provide specialized implementations tailored to their specific requirements.

Types of Inheritance in Java

There are various types of Inheritance in Java like :

Types of Inheritance in Java

Single Inheritance 

When a single class inherits from another single class, it is called Single Inheritance. Example: Only single class - Class B inherits from single class - Class A.

Know about Single Inheritance in Java in detail.

MultiLevel Inheritance

When there is a chain of inheritance, it is called MultiLevel Inheritance. Example: Single class C inherits from class B which further inherits from class A. 

Hierarchical Inheritance

When two or more classes inherit a single class, it's called Hierarchical Inheritance. Example: class B and class C inherits from single class A.

Multiple Inheritance

When a single class inherits from multiple classes, it's called Multiple Inheritance. Example: Class C inherits from class A and class B. 

Java doesn’t allow multiple Inheritance to avoid the ambiguity caused by it. 

Hybrid Inheritance

Hybrid inheritance in Java is a combination of two or more types of inheritances. Example: Class D inherits from class C and class B, and both the classes B and C inherit from class A. Java doesn’t support Hybrid inheritance as well.


We have covered these in detail in our other blogs.

Check out this article - Upcasting and Downcasting in Java

Inheritance with an Example

Let’s dive deeper now with the help of an example,

We have two classes, CAR and TRUCK; both of these have some properties in common (like color, motor, number of tyres, etc.) as both are Vehicles. So, Inheritance helps us move those common properties under a class - VEHICLE and both CAR and TRUCK could inherit from it. 

 

Hence forming a structure like:

Inheritance

where VEHICLE is our parent class and CAR, TRUCK are our child classes.

Example

  • Java

Java

class Vehicle{
   String color;
   int maxspeed;
  
   public void print(){
       System.out.println("Vehicle Color: "+ color);
       System.out.println("Vehicle MaxSpeed: "+ maxspeed);
   }
}

// Car class has Vehicle class as its parent class
class Car extends Vehicle{
   int gears;
   boolean isconvertible;
  
   // default function
   void Carprint(){
       System.out.println("Car gears: "+ gears);
       System.out.println("Is car convertible: "+ isconvertible);
   }
}

class VehicleUse{
   public static void main (String[] args) {
       Vehicle v = new Vehicle();
       v.print();
       System.out.println();
      
       Car c = new Car();
       c.gears = 10;

       // Car class can access the data members and
       //functions of its parent class i.e. Vehicle Class
       c.color = "Brown";
       c.print();
       System.out.println();
      
       c.Carprint();
   }
}

Output:

Vehicle Color: null
Vehicle MaxSpeed: 0

Vehicle Color: Brown
Vehicle MaxSpeed: 0

Car gears: 10
Is car convertible: false

 

Initially, the Output is Vehicle Color: null and Vehicle MaxSpeed: 0 as the value is not initialized.

The access modifiers also play an essential role. If we make MAXSPEED (in VEHICLE Class) as Private, we can access it neither as VEHICLE USE Class nor as CAR Class’s object as it would then be private to the objects of VEHICLE Class.  

 

Time and Space Complexity

Time Complexity:  O(1) as data members and functions are called directly.

Space Complexity:  O(1) as no extra space is required.

You can also read about the Multiple Inheritance in Java and  Swap Function in Java

Overwrite Functions

Inheritance In Java also allows overwriting functions in subclasses that are already defined in the base class. So, in CAR Class, if we had PRINT() Function instead of CARPRINT(). Now, the PRINT() function is also present in the VEHICLE Class.

So, on executing 

Car c = new Car();

c. print();  

in VehicleUse class, the java compiler would have two options, i.e., the Print() function of Car class and Vehicle Class. 

So, here bottom to top hierarchy is followed - i.e., whenever a function is called, 

 

3. Parent’s Parent class

2. Parent Class (Vehicle class) 

1. Car Class (current class)

 

I.e., the print() function is first looked at in the Car class. Since the function is found, it is executed. Otherwise, moving up, the print() function would have been looked up in Parent Class, and even then, if not found, the function is then looked up in the Parent’s Parent Class.

 

So, c.print() calls the print function of the CAR class.

 

Inheritance in Java Constructors And Destructors

Inheritacne in Java

Whenever an object of subclass (i.e., C here) is created, 

The order of constructors called is top to bottom I,e: 

FIRST:  A’s Constructor is called

SECOND  B’s Constructor is called

THIRD:  C’s Constructor is called

 

However, when a program ends and objects are destroyed by the garbage collector, The order of destructors called is opposite i.e.

 

FIRST:  C’s Destructor is called

SECOND  B’s Destructor is called

THIRD:  A’s Destructor is called

​​Advantages of Inheritance in Java:

  • Code Reusability: Inheritance promotes the reuse of existing code, reducing redundancy and improving efficiency by inheriting fields and methods from a superclass.
  • Hierarchy and Organization: Inheritance facilitates the creation of hierarchical relationships among classes, reflecting real-world relationships and enhancing code organization.
  • Polymorphism: Through inheritance, Java supports polymorphism, enabling objects of different subclasses to be treated interchangeably through their common superclass interface.
  • Extension and Specialization: Subclasses can extend and specialize the functionality of their superclass, adding new features or modifying existing ones without altering the superclass itself.
  • Maintenance and Updates: Changes made to the superclass automatically propagate to its subclasses, ensuring consistency and reducing the effort required for maintenance and updates.

​​Disadvantages of Inheritance in Java:

  • Coupling: Inheritance can lead to tight coupling between classes, where changes to the superclass may affect subclasses, potentially introducing unintended consequences.
  • Inflexibility: Inheritance creates a rigid class hierarchy, making it challenging to adapt to changing requirements or to reuse classes in different contexts.
  • Complexity: Deep inheritance hierarchies can become complex and difficult to understand, especially for large-scale projects, leading to maintenance issues and decreased code readability.
  • Overhead: Inheritance introduces overhead in terms of memory consumption and runtime performance, particularly when dealing with deep inheritance chains or multiple levels of abstraction.
  • Misuse: Improper use of inheritance, such as excessive subclassing or violating the "is-a" relationship, can result in poorly designed and difficult-to-maintain code.

Frequently Asked Questions

Where is inheritance used in Java? 

Inheritance in Java helps us create new classes upon existing classes. So, when we inherit from an existing class, we can reuse methods and data members of the parent class or add new methods and members in our current class.

Is Multiple Inheritance in Java supported?

When one class extends more than one class, then this is called multiple Inheritance. Java doesn’t allow multiple Inheritance to avoid the ambiguity caused by it. One example of such a problem is the diamond problem that occurs in multiple Inheritance.

However, C++ supports Multiple Inheritance via using virtual Inheritance(This does not exist in Java).  

            A 
            / \ 
          B   C 
            \ / 
            D

So, D class ideally inherits 2 copies of A class but virtual Inheritance helps us keep on one copy inherited from the base class (B or C) which D inherits first sequentially.

What is the real-life application of inheritance in Java?

In Java, a real-life application of inheritance is evident in graphical user interface (GUI) frameworks like Swing and JavaFX. These frameworks utilize inheritance to create reusable components (e.g., buttons, text fields) with common behaviors and properties.

Conclusion

In this blog, we learned about Inheritance in Java. It is a powerful mechanism that fosters code reuse, promotes hierarchy and organization, and enables polymorphism. While it offers numerous advantages such as improved efficiency and maintenance, it's essential to be mindful of potential drawbacks like tight coupling and complexity.
Recommended Reading:


Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, Uber, Microsoft, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.


For a Complete tutorial on Object-Oriented Programming in Java, you should watch the below video.

Previous article
Aggregation in Java
Next article
Single Inheritance in Java
Live masterclass