Advantages and Disadvantages of Inheritance in Java

Inheritance is one of the pillars of the Java programming language. Learning OOP (Object Oriented Programming) without knowing and understanding the concept of Inheritance, its pros and cons are incomplete.

Inheritance is a process in which a class acquires all the data members and its parent class methods. The basic idea behind it is that you create new classes based on the existing classes with additional data and methods.

Example:

In the above example, there are two classes SuperHello and Sub. Using the keyword extends, the Sub Class inherits the SuperHello Class.

Java Inheritance Example

Output:
Student name who do programming is: Hello
Programmer Language is: JAVA

According to the above program, the Class Student is inherited by the Class Programming. Therefore Programming class can both its data and its superclass data.

Types of Inheritance in Java

  • Single Inheritance: It is the simplest Inheritance. According to this, a class inherits another one.
  • Multilevel Inheritance: In multilevel Inheritance, one class inherits from a class that inherits from another class. It forms a chain-like structure. For example, a puppy inherits from the Dog class, and the Dog class inherits from the Animal class.
  • Hierarchical Inheritance: In Hierarchical Inheritance, two or more classes inherit a single class. For example, Dog and Lion class inherit from the Animal class.
  • Hybrid Inheritance: It is a combination of single, multilevel, and Hierarchical Inheritance.

Please note that Java does not support Multiple Inheritance.

Advantages of Inheritance

Minimizing duplicate code: Key benefits of Inheritance include minimizing the identical code as it allows sharing of the common code among other subclasses.

Flexibility: Inheritance makes the code flexible to change, as you will adjust only in one place, and the rest of the code will work smoothly.

Overriding: With the help of Inheritance, you can override the methods of the base class.

Data Hiding: The base class in Inheritance decides which data to be kept private, such that the derived class will not be able to alter it.

Disadvantages of Inheritance

No Independence: One of the main disadvantages of Inheritance in Java is that two classes, both the base and inherited class, get tightly bounded by each other. In simple terms, Programmers can not use these classes independently of each other.

Decreases Execution Speed: Another con of Inheritance is that it decreases the execution speed because Inheritance execution takes time and effort.

Refactoring the Code: If the user deletes the Super Class, then they have to refactor it if they have used it.

Leave a Reply

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