Do you think IIT Guwahati certified course can help you in your career?
No
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.
In this blog, we'll delve into the intricacies of inheritance in Java, exploring its principles, syntax, and practical applications.
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.
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 :
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.
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.
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:
where VEHICLE is our parent class and CAR, TRUCK are our child classes.
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.
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
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: