In this tutorial, we will learn a very important chapter Inheritance in Java. Inheritance is one of the main pillars of OOPs (Object Oriented Programming) concept. It is a technique of organizing information in the hierarchical form. 

Inheritance in Java provides a mechanism for the users to reuse the existing code within the new applications. It does this by allowing the programmer to build a relationship between a new class and existing class and define a new code in terms of existing code.

This tutorial will guide you on how to derive new classes from existing classes, and the advantages of inheritance in java. 

What is Inheritance in Java

The technique of creating a new class by using an existing class functionality is called inheritance. In other words, Inheritance in Java is a process where a child class acquires all the properties and behaviors of the parent class. The existing class is called parent class and the new class is called child class.

Let us take real-time examples to understand the concept of inheritance.

Realtime Example of Inheritance in Java

1. In the real world, a child inherits the features of its parents such as the beauty of mother and intelligence of father as shown in the below fig. 
Realtime example of inheritance in Java.
Inheritance represents the IS-A relationship, also known as a parent-child relationship.

What is Is-A relationship in Java

1. Is-A relationship in java represents Inheritance. It is implemented using "extends" keyword.
2. It is used for code reusability.

All the classes extends java.lang.object by default. This is a very good example of Is-A relationship. An object is the root class of all the classes in Java. Therefore, by default, every class is the subclass of java.lang.object.

So, every class acquires its properties from the object class. Hence, we can say that an object class is the superclass of every class.
For example:
    class A 
             // some statements
The compiler will treat the above code like this:
    class A extends Object
             // some statements.
Look at the below figure to understand different forms of relationships in java.

Is-A relationship in Java

Important Terminology:

1. Superclass/Parent class: 

The class from where a subclass inherits the features is called superclass. It is also called a base class or parent class. 

2. Subclass/Child class:

A class that inherits all the members (fields, method, and nested classes) from the other class is called subclass. It is also called a derived class, child class or extended class.

A derived class extends its features by inheriting all the features of another class, called base class and can also add its own features. The base class remains unchanged.

Creating Subclass in Java

A subclass can be created by using the extends keyword. The syntax for declaring a subclass is shown as follows:
class subclassName extends superclassName
    Variables of subclass
    Methods of subclass
       class, and extends are keywords.

The extends keywords indicates that you are deriving a new class (Derived class) from the existing class (Base class). In simple words, the extends keyword is used to make the relationship between two classes. Once the relationship is done, Automatically, the code is reusable. 

Note: 1. When you declare a derived class, no memory is allocated but memory is allocated when you create an object.
2. The subclass can inherit variables and methods of superlcass if they are not declared as private.

Consider the derivation of a new class from an existing class as shown in Fig.
Base class and derived class relationships
As shown in the above figure, the derived class acquires all the features of the base class (A and B) and adds its own feature (C). The arrow in the diagram expresses the concept of derivation. The direction from the derived class towards the base class represents that the derived class has all the features of the base class and not vice-versa.

Note: Inheritance is a compile-time mechanism. A parent class can have any number of derived class but a derived can have only one parent class. Therefore, Java does not support multiple inheritance. 

3. Re-usability: 

A mechanism that facilitates to reuse the fields and methods of the existing class into the new class is known as reusability. When you create a new class, you can use the same fields and methods already defined in the previous class. This is called reusability.

How features of Superclass are inherited in Subclass?

Let's take a simple example program to understand this concept. We will take the above diagram for example.
1. The base class is a superclass of the derived class.
2. The derived class is a subclass of the base class.
3. features() method of the base class is inherited in the derived class. 

Let's consider the following source code.
Program source code 1:
    package inheritance; public class BaseClass { void features(){ System.out.println("Feature A"); System.out.println("Feature B"); } } public class DerivedClass extends BaseClass { void ownFeature(){ System.out.println("Feature C"); } } public class InheritanceTest { public static void main(String[] args) { // Create an object of the derived class. DerivedClass d = new DerivedClass(); // Call features() method from the derived class using object reference variable d. d.features(); // Call ownFeature() method using reference variable d. d.ownFeature(); } }
    Output: Feature A Feature B Feature C
When an object of DerivedClass is created, it contains a copy of BaseClass within it. It means that there is a relationship between DerivedClass and BaseClass. This is the reason that the members of superclass are available to subclass.

In the above program, we did not create superclass object but still, a copy of it is available to the subclass. This is because the subclass object contains superclass object. 

Uses of Inheritance in Java

We use inheritance in java for the following reasons:
1. We can reuse the code from the base class.
2. Using inheritance, we can increase features of class or method by overriding.
3. Inheritance is used to use the existing features of the class.
4. It is used to achieve runtime polymorphism i.e method overriding.
5. Using inheritance, we can organize the information in the hierarchal form.

Let's take a program to understand the uses of inheritance in Java. Consider the following program source code without using inheritance.
    class A { void m1() { ....} } class B { void m1() {....} void m2() {....} } class C { void m1() {....} void m2() {....} void m3() {.... } }
In the above program, class A contains one functionality i.e. one m1() method, class B contains two methods m1() and m2(), and class C contains three methods m1(), m2(), and m3(). So, what are the disadvantages of this code?

There are two disadvantages of this code.
1. First is code duplication.
2. Second is the length of the code.

Since in this code, the m1() method defined 3 times, m2() method defined two times. Here, the redundancy of the code is code duplication. In the real-time project, code duplication is not allowed. Due to the duplication, the length of the code is also increased.

Therefore, we can reduce the length of the code by creating a relationship between two classes using the inheritance concept. but how?

We will use extends keyword to make a relationship between two classes. Once the relationship is done, the code is automatically reusable. Let us consider the program source code with inheritance.
    class A { void m1() { ... } } class B extends A { void m2() {... } } class C extends B { void m3() {.... } }
In this way, we can reduce the length of the code using inheritance concepts in Java applications. m1() method will automatically come in class B, m1() and m2() methods will come in the class C.This is the main advantage of using inheritance in Java.

How is Inheritance implemented/achieved in Java

Inheritance in Java can be implemented or achieved by using two keywords:
1. extends: extends is a keyword that is used for developing the inheritance between two classes and two interfaces. Note that a class always extends another class. An interface always extends another interface and can extend more than one interface.

2. implements: implements keyword is used for developing the inheritance between a class and interface. A class always implements the interface.

Role of Constructor in Java Inheritance

The role of constructor in inheritance is that the constructor in the superclass is responsible for building an object of the superclass and the constructor of a subclass builds an object of the subclass. When the constructor of a subclass is called during the object creation, by default, it calls the default constructor of the superclass.

The superclass constructor can be called using keyword super from the subclass constructor. It must be the first statement in a constructor. We can call other constructors of same class using this keyword but you cannot call a subclass constructor from the superclass constructor.

What are advantages of Inheritance in Java

The advantages of inheritance in Java are as follows:
1. One of the main advantages is that you can minimize the length of the duplicate code in an application by putting the common code in the superclass and sharing amongst several subclasses.

2. Due to reducing the length of the code, redundancy of the application is also reduced. 
3. Inheritance can also make application code more flexible to change because a class that inherits from the superclass, can be used interchangeably.

Let's take a simple scenario to understand the advantage of using inheritance in java programming.


Suppose that a student has attributes like name, age, and location. This class exists for a long time. After some time, we need to add one attribute pan card of the student. So what will we have all the options?

1. The first option is that we can modify the class student.
2. The second option is we need to extend student class and add an attribute in the new class.
➲ The first option is the violation of principles of java 'Java classes are not open for modifications'. So, we should not modify the existing one. This will increase unit testing to be done again for the existing class.

➲ The second option is without disturbing the existing class, we can add one variable to the other class by making a subclass. So only unit testing will need for the child class, not for the parent class.

Let's look at the following program source code related to the above scenario.
Program source code 2:
    package inheritance; public class Student { String name; int age; String location; } public class Pancard extends Student { int pancard; }

Important Java Inheritance Rules

1. We cannot assign superclass to subclass.
2. We cannot extend the final class.
3. A class cannot extend itself.
4. One class can extend a single class.

5. We cannot extend a class having an private constructor but if we have the private constructor as well as public constructor then we can extend superclass to subclass. In this case, the only public constructor will work.

6. If we assign subclass reference to superclass reference, it is called as dynamic method dispatch in java.

7. Constructor, Static initialization block (SIB), and Instance initialization block (IIB) of the superclass cannot be inherited to its subclass but they are executed while creating an object of the subclass.

Let's take an example program based on constructor, static initialization block, and instance initialization block.
Program source code 3:
    package inheritance; public class A { // Declare an instance variable and initialize value 10. int a=10; // Declare a default constructor. A() { System.out.println("Class A constructor"); } // Declare a static block. static { System.out.println("Class A SIB"); } // Declare an instance block. { System.out.println("Class A IIB"); } } public class B extends A{ int b=20; } public class Myclass { public static void main(String[] args) { // Create an object of class B. B obj=new B(); System.out.println("Value of a: " +obj.a); System.out.println("Value of b: " +obj.b); } }
    Output: Class A SIB Class A IIB Class A constructor Value of a: 10 Value of b: 20

8. A static method of the superclass are inherited to the subclass as a static member and non-static method are inherited as a non-static member only. Let's understand it by an example program.
Program source code 4:
    package inheritance; public class A { // Declare an instance variable, static variable and initialize values. int a=10; // Non-static variable. static int b=30; // Static variable. static void show() { System.out.println("Static method of class A"); } void display() { System.out.println("Non-static method of class A"); } } public class B extends A { static int a=20; int b=40; void show() { // Compile time error because the instance method cannot override the static method from class A. System.out.println("Non-static method of class B"); } static void display() { // Compile time error because the static method cannot override instance method from class A. System.out.println("Static method of class B"); } public static void main(String[] args) { // Create an object of class B. B obj=new B(); System.out.println("Value of a: " +B.a); System.out.println("Value of b: " +obj.b);; B.display(); } }
    Output: Value of a: 20 Value of b: 40 Exception in thread "main" java.lang.Error: Unresolved compilation problem: This instance method cannot override the static method from A
Final words 
Hope that you have enjoyed the article Inheritance in Java. Uses and advantages of inheritance are also important to know. In the next tutorial, we will discuss different types of inheritance example programs.
Thanks for reading!
Next ➤ Superclass and Subclass in Java ⏪ Prev Next ⏩