Browse Categories
Choose your Categories to read

Inheritance In Java

Raksha Jain
Oct 29, 2021

Introduction

 

All of our programming languages are classified into procedural languages and object-oriented programming languages. 

Some of the examples of procedural languages include COBOL, Fortran, etc. These languages do not have any data hidden, and everything is freely available. However, object-oriented programming languages like C + + Java have various functionalities like Data abstraction, Data hiding, Inheritance, etc.

 

 So, object-oriented programming languages have the edge over procedural languages as:

  1. Data is hidden and cannot be accessed by external functions, hence ensuring security.
  2. Objects may communicate with each other via functions. 
  3. New data can be added whenever necessary 
  4. Emphasis on data and data structures are designed such that they characterize objects.

 

One of the most important features of object-oriented programming languages is Inheritance.

 It has various advantages like :

  1. Concept of Reusability: We only have to add additional features in the new class, and we could use the already defined features from another class. Hence, we need to enhance the existing features or create new features while defining a new class.  
  2. Concept of Deliverability: Child class can inherit all or a few of the features from the parent class.

 

Some Important Terms of Inheritance

 

There are some important terms in Inheritance in Java-like: 

  1. CLASS: It is a template or blueprint with some common properties from which an object can be created.
  2. SUBCLASS/ CHILD CLASS: It is the class that inherits features from the parent class.
  3. SUPER CLASS/PARENT CLASS: It is the class from which subclasses inherit traits.

 

Note:   Parent class is also known as Super Class and Base Class.

The child class is also known as Subclass and Derived class.

 

Inheritance with an Example

 

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.

Example

 

class Vehicle{
    String color;
    int maxspeed;
    
    public void print(){
        System.out.println("Vehicle Color: "+ color);
        System.out.println("Vehicle MaxSpeed: "+ maxspeed);
    }
}

// Car class has Vehicle class as its parent class
class Car extends Vehicle{
    int gears;
    boolean isconvertible;
    
    // default function
    void Carprint(){
        System.out.println("Car gears: "+ gears);
        System.out.println("Is car convertible: "+ isconvertible);
    }
}

class VehicleUse{
    public static void main (String[] args) {
        Vehicle v = new Vehicle();
        v.print();
        System.out.println();
        
        Car c = new Car();
        c.gears = 10;

        // Car class can access the data members and
        //functions of its parent class i.e. Vehicle Class
        c.color = "Brown";
        c.print();
        System.out.println();
        
        c.Carprint();
    }
}

 

Output:

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.

 

Overwrite Functions

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 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

 

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.
 

MultiLevel Inheritance

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.

 

Frequently Asked Questions

 

  1. What are the types of inheritance in Java?
    The different types of Inheritance in Java are Single, MultiLevel and Hierarchical Inheritance.

     
  2. 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.

     
  3. What are the benefits of inheritance? 
    Inheritance in Java has various advantages like:
    1. It promotes reusability:  When a class inherits or derives another class, it can access all the functionality of the inherited class.
    2. Reusability enhances reliability. The base class code will be already tested and debugged.
    3. As the existing code is reused, it leads to less development and maintenance costs.
    4. Inheritance makes the sub classes follow a standard interface.
    5. It helps to reduce code redundancy and supports code extensibility.
    6. It facilitates creation of class libraries.

     
  4. 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.
     

Key Takeaways

  

In this blog, we learned a lot about Inheritance in Java. 

 

  • Inheritance is one of the primary key features of object-oriented programming languages like Java.
  • It promotes the concept of reusability as we only have to add additional features in the new class, and we could use the already defined features from another class.
  • We further learned that when a data function is overwritten, we follow the bottom-to-top hierarchy, i.e., the function is first looked at in the current class. If the function is not found, we look for the function in Parent Class, and even then, if not found, the function is then looked up in the Parent’s Parent Class.

 

Check out more blogs on different types of Inheritance in Java like Single, MultiLevel, Multiple, Hybrid and Hierarchical Inheritance to read more about these topics in detail. And if you liked this blog, share it with your friends!
 

Was this article helpful ?
0 upvotes