Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Java inheritance is a key feature of object-oriented programming that enables a class to acquire properties and behaviors (fields and methods) from another class. This mechanism supports code reusability and enhances the structure of programs through hierarchical relationships between classes.
In this article, we will learn the concept of inheritance in Java, including its types, benefits, and practical implementations. We'll also learn how to use inheritance effectively with examples for better understanding.
What is Inheritance in Java?
Inheritance in Java 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.
Importance of 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: Java supports polymorphism through inheritance, 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.
Core Terminologies of Java Inheritance
Here are the essential terminologies associated with Java inheritance:
Class: A blueprint for creating objects that encapsulate data and methods.
Subclass (Derived Class or Child Class): The class that inherits properties and behaviors from another class.
Superclass (Base Class or Parent Class): The class whose members are inherited by the subclass.
extends Keyword: Used to define the inheritance relationship between a subclass and a superclass.
Method Overriding: The ability of a subclass to provide a specific implementation of a method already defined in its superclass.
IS-A Relationship: Represents inheritance in Java, where a subclass is a type of the superclass.
Constructors and Inheritance: While constructors are not inherited, a subclass can invoke a superclass constructor using super().
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 in Java
Single inheritance is a type of inheritance where a subclass inherits the properties and behaviors from a single superclass.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class TestSingleInheritance {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}
You can also try this code with Online Java Compiler
Hierarchical inheritance means that multiple classes inherit from a single parent class.
Example:
class Animal {
void eat() {
System.out.println("Animal eats.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows.");
}
}
public class TestHierarchicalInheritance {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
Cat c = new Cat();
c.eat();
c.meow();
}
}
You can also try this code with Online Java Compiler
Hybrid inheritance is a combination of two or more types of inheritance. Java supports hybrid inheritance through interfaces.
Example:
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
interface C extends A {
void methodC();
}
class D implements B, C {
public void methodA() {
System.out.println("Method A");
}
public void methodB() {
System.out.println("Method B");
}
public void methodC() {
System.out.println("Method C");
}
}
public class TestHybridInheritance {
public static void main(String[] args) {
D obj = new D();
obj.methodA();
obj.methodB();
obj.methodC();
}
}
You can also try this code with Online Java Compiler
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.
What are the 4 types of inheritance in Java?
Single, Multilevel, Hierarchical, and Multiple (using interfaces) are the four main types of inheritance supported in Java.
What is the syntax of inheritance?
The syntax of inheritance in Java uses the extends keyword: class SubclassName extends SuperclassName { // body }
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: