Java Inheritance – Types & Importance of Inheritance with Real-life Examples!
Inheritance is one of the most important concepts of Object-Oriented Programming. Inheritance is the capability of one class to inherit capabilities or properties from another class in Java. For instance, we are humans.
We inherit certain properties from the class ‘Human’ such as the ability to speak, breathe, eat, drink, etc.We can also take the example of cars. The class ‘Car’ inherits its properties from the class ‘Automobiles’ which inherits some of its properties from another class ‘Vehicles’.
The object-oriented languages express this inheritance relationship by allowing one class to inherit from another. Thus a model of these languages is much closer to the real-world.
The principle behind this kind of division is that each subclass (child-class) shares common characteristics with the class from which it is derived.
The above figure illustrates:
- Automobiles and Pulled Vehicles are subclasses of Vehicles.
- Vehicles are the base class or superclass of Automobiles and pulled Vehicles.
- Car and Bus are sub-classes or derived classes of Automobiles.
- Automobiles are the base class or superclass of Car and Bus.
Why Java Inheritance?
There are several reasons why inheritance was introduced into Object-oriented languages. We will discuss some major reasons behind the introduction of inheritance.
- The capability to express inheritance relationships ensures the closeness with the real-world models.
- Another reason is the idea of reusability. One can derive a new class (sub-class) from an existing class and add new features to it without modifying its parent class. There is no need to rewrite the parent class in order to inherit it.
- One reason is the transitive nature. If class A inherits properties from another class B, then all subclasses of A will automatically inherit properties from B. This property is called the transitive nature of inheritance.
Note: A subclass defines only those features that are unique to it.
For example, the class Student inherits from the class Person. Then although Student is a person, the reverse is not true. A Person need not be a Student. The class Student has properties that it does not share with class Person.
For instance, the Student has a marks-percentage, but the Person does not have.
Important Terms in Java Inheritance
1. Class: Class is a user-defined datatype in Java that is basically a group of objects. It is a blueprint or template from which we create objects.
2. Super Class: The class whose features and functionalities are being inherited or used is known as the superclass or a base class or a parent class.
3. Sub Class: The class that inherits the properties and features from another class is known as a subclass or a derived class or extended class or child class. The subclass can add its own features and functions in addition to the fields and methods of its superclass or the parent class.
4. The extends keyword: The keyword extends is used by child class while inheriting the parent class.
5. The super keyword: The super keyword is similar to this keyword. The following are some cases where we use super keyword :
- There are some situations where the members of the superclass and the subclass have the same names, then the super keyword is used to differentiate the members of the superclass from the members of the subclass.
- To invoke the superclass constructor from the subclass.
Syntax of using Inheritance in Java:
We already know that to inherit a class, we use the extends keyword. The syntax of using inheritance in Java is:
class BaseClass { //methods and fields } class DerivedClass extends BaseClass { //methods and fields }
Code to explain Java Inheritance:
package com.techvidvan.inheritance; //Base class class Person { String name = "John"; int age =17; String city = "Delhi"; public void show() { System.out.println("Student inheriting properties from Person:\n"); } } //child class class Student extends Person { // defining additional properties to child class int marks = 78; String tutorial = "TechVidvan Tutorial of Java"; public static void main(String args[]) { Student obj = new Student(); obj.show(); System.out.println("Name of the student is: " + obj.name); System.out.println("Age of the student is: " + obj.age); System.out.println("Student lives in: " + obj.city); System.out.println("Student learns from: " + obj.tutorial); System.out.println("Marks obtained by the student is: " + obj.marks); } }
Output:
Name of the student is: John
Age of the student is: 17
Student lives in: Delhi
Student learns from: TechVidvan Tutorial of Java
Marks obtained by the student is: 78
From the above program, we can say that Student IS-A Person. This means that a derived class has an IS-A relationship with the base class. This inheritance is called IS-A relationship between the child and parent class.
In the above code, when an object of Student class is created, a copy of all the methods and fields of the superclass acquire memory in this object. Therefore, we are able to access the members of the superclass by using the object of the subclass.
Please note that during inheritance, we create the object of only the subclass, not the superclass.
Types of Java Inheritance
From the above diagram, we can see that there are five types of inheritance in Java. They are classified on the basis of the number of super and subclasses.
There is an exception that ‘multiple inheritance’ is not directly supported by classes in Java. Rather we use interfaces to implement multiple inheritances in Java.
Now, we will discuss each type of inheritance with examples and programs.
1. Single Inheritance in Java
In single inheritance, there is a single child class that inherits properties from one parent class.
In the following diagram, class A is a base class that is derived from class B. It is also known as single-level inheritance.
Syntax of single Inheritance:
class A { //methods and fields } Class B extends A { //methods and fields
Code to illustrate Single Inheritance:
package com.techvidvan.inheritance; //Base class class Person { String name="John"; public void show() { System.out.println("Student inheriting properties from Person"); } } //child class class Student extends Person { // defining additional properties to child class String course = "Techvidvan's Java Course"; public void show1() { System.out.println("I am a Student who belongs to Person class"); } public static void main(String args[]) { Student obj = new Student(); obj.show(); obj.show1(); System.out.println("Name of student: " +obj.name); System.out.println("Course opted by the student: " +obj.course); } }
Output:
I am a Student who belongs to Person class
Name of student: John
Course opted by the student: Techvidvan’s Java Course
2. Multilevel Inheritance in Java
In this type of inheritance, the child or derived class inherits the features of the superclass and simultaneously this child class acts as a superclass for another derived class.
In the following diagram, class A is a base class that is derived from class B, which in turn, acts as a base class for a derived class C.
Code to illustrate Multilevel Inheritance:
package com.techvidvan.inheritance; //Base class class Person { public void show() { System.out.println("Student inheriting properties from Person"); } } class Student extends Person { public void show1() { System.out.println("I am a Student who belongs to Person class"); } } //child class class EngineeringStudent extends Student { // defining additional properties to the child class public void show2() { System.out.println("Engineering Student inheriting properties from Student"); } } public class MultilevelDemo { public static void main(String args[]) { EngineeringStudent obj = new EngineeringStudent(); obj.show(); obj.show1(); obj.show2(); } }
Output:
I am a Student who belongs to Person class
Engineering Student inheriting properties from Student
3. Hierarchical Inheritance in Java
In Hierarchical Inheritance, one class acts as a superclass (base class) for more than one subclass. More than one subclass can inherit the features of a base class.
In the following diagram, class A is a base class for the derived classes B, C, and D.
Code to illustrate Hierarchical Inheritance:
package com.techvidvan.inheritance; //Base class class Person { public void show() { System.out.println("I am a Person"); } } //child class1 class Student extends Person { public void show1() { System.out.println("I am a Student who is Person "); } } //child class2 class Teacher extends Person { // defining additional properties to the child class public void show2() { System.out.println("I am a Teacher who is a Person"); } } //child class3 class Doctor extends Person { // defining additional properties to the child class public void show3() { System.out.println("I am a Doctor who is a Person"); } } public class HierarchicalInheritance { public static void main(String args[]) { Teacher teacher = new Teacher(); Student student = new Student(); Doctor doctor = new Doctor(); student.show(); student.show1(); teacher.show2(); doctor.show3(); } }
Output:
I am a Student who is Person
I am a Teacher who is a Person
I am a Doctor who is a Person
4. Multiple Inheritance in Java
In Multiple Inheritance, one child or subclass class can have more than one base class or superclass and inherit features from every parent class which it inherits.
We have already discussed that Java does not support multiple inheritances with classes. We can achieve multiple inheritances only with the help of Interfaces.
In the following diagram, Class C inherits from interfaces A and B.
Code to illustrate Multiple Inheritance:
package com.techvidvan.inheritance; //base interface1 interface Moveable { public void run(); } //base interface2 interface Speakable { public void speak(); } //child interface inheriting two base interfaces interface Ability extends Moveable, Speakable { public void show(); } class Person implements Ability { @Override public void run() { System.out.println("I can run !!"); } @Override public void speak() { System.out.println("I can speak !!"); } @Override public void show() { System.out.println("I am a person, I can speak and run !!"); } } public class MultipleInheritance { public static void main(String[] args) { Person obj = new Person(); obj.run(); obj.speak(); obj.show(); } }
Output:
I can speak !!
I am a person, I can speak and run !!
5. Hybrid Inheritance in Java
It is a combination of two or more types of inheritance. The hybrid inheritance is also not possible with classes because Java doesn’t support multiple inheritance with classes. We can achieve hybrid inheritance only through Interfaces.
In the following diagram, class A is the base class for subclasses B and C. And, class D inherits both the classes B and C.
Code to illustrate hybrid Inheritance:
package com.techvidvan.inheritance; //base class 1 class Ability { public void show() { System.out.println("I am a person, I can speak and run !!"); } } //child interface 1 interface Moveable { public void run(); } //child interface2 interface Speakable { public void speak(); } //child class inheriting two base interfaces class Person extends Ability implements Moveable, Speakable { @Override public void run() { System.out.println("I can run !!"); } @Override public void speak() { System.out.println("I can speak !!"); } } public class HybridInheritance { public static void main(String[] args) { Person obj = new Person(); obj.run(); obj.speak(); obj.show(); } }
Output:
I can speak !!
I am a person, I can speak and run !!
Inheritance in OOP with Real-time Example
Consider an application Polygon that represents different types of Shapes.
We are supposed to create two different types of Polygons, one will be Rectangle and the other will be Triangle.
Let’s compare and study the two different approaches of coding with a structured and object-oriented programming perspective.
Structural approach:
Using a structured programming approach, we will create two functions:
- One to get the Number of sides of a polygon.
- And the other to calculate the area.
The working of these functions remains the same across two different shapes.
OOP’s approach:
Using the OOPs programming approach, we would create two different classes.
- Each having implementation of thegetNumberOfSides() and getArea() functions.
- This will reduce extra work.
Change Request in Software
Suppose there is a change in the functionality of the software. You are supposed to add the functionality of finding the area of a Square.
Let’s see how to deal with this problem with both approaches.
Structural approach:
If we want to add a new feature using a functional or traditional methodology, we will need to modify the getArea() function which is already tested and baselined. If we add new functionality of finding the area of a Square then our code will look like:
OOP’s approach:
Using the Object-Oriented approach, you just require to add a new class Square which will have the unique functionality of finding the area of Square. There is no need to change the piece of code that is already tested by using this approach.
Another Change Request
Suppose if there are some more changes required in the software. For example, if you want to add a Shape Parallelogram with its own unique requirements.
Structural approach:
If we want to add the Parallelogram Shape in the existing class using the structural approach, then we will definitely need to make changes in the existing code.
OOP’s approach:
If we want to add another shape in the existing class using the object-oriented approach, we will just need to create a new class Parallelogram with its unique methods. The diagram below illustrates the same –
So, even though at the initial stage, the structural programming was appearing to be an easy approach, but as the complexity of the code increases and there are more changes in the requirements then this approach fails.
Eventually, the Object-Oriented approach wins in the long term.
But you might be thinking that across all the classes, we have to write a repeated piece of code for each class.
To overcome this problem of repetition, we can create a parent class called “Shape” and implement the same function of getNumberOfSides and getArea. Then we will create the child classes that will inherit this parent class Shape.
So that they will have access to getNumberOfSides and getArea functions in the Shape class.
There is no need to declare these functions in each class. This concept is called Inheritance in java.
So you can clearly see that with the help of the Inheritance approach of OOP we can easily update our code without disturbing the code which is already tested.
Summary
Inheritance is the most essential feature of Object-oriented programming. It helps in reducing the complexity of writing very large codes as it provides the code reuse feature.
Coming to the end of this article, we have learned the basics of inheritance in Java, the importance of inheritance as well as various types of inheritances in Java with coding examples and diagram illustrations so that you can understand the concept easily.
We also discussed the importance of inheritance with some real-world examples that can be further helpful for you in programming in the real world.
Thank you for reading our article. If you have any queries or suggestions related to Java Inheritance, let us know by leaving a comment below.