Inheritance in Java

Inheritance in Java is an important aspect of OOP (Object Oriented Programming). It is a method in Java by which a class can inherit the properties (fields and methods) of another class. Inheritance in Java means creating a new class based on an existing class. A child class that inherits from parent class can reuse the methods and fields of that class. You can also add new fields and methods to the existing category.

Why Do We Need Inheritance?

1) Reusability of code : The parent class code can be accessed in child class and we can reuse parent class code.

2) Reduce development Efforts : Inheritance saves development time and cost.

How to achieve Inheritance

We can achieve inheritance mechanism simply by using “extends” keyword in java, no other code needs to write.

Inheritance syntax in java

public class Child extends Parent{

// fields and methods to write business code

}

Inheritance  example

In the below example, class “Parent” is super class which is getting extended by sub class “Child“. When “Child” class uses extends keyword then automatically “Parent” class properties gets inherits into child class and properties can be accessed via child class reference.

package com.ajitation;

public class Parent {

public void parentMethod() {

System.out.println(“Parent Class Method called”);

}

}

public class Child extends Parent{

public void childMethod() {

System.out.println(“Child Class Method called”);

}

public static void main(String[] args) {

Child child = new Child();

child.parentMethod(); //extended Parent class method and calling via child class reference

child.childMethod();

}

}

Output :

Parent Class Method called

Child Class Method called

Different types of inheritance

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance
5) Hybrid Inheritance

Inheritance real time example :

a) Microsoft Office comes with multiple versions such as MS Office 2000, 2003, 2007, etc. but it doesn’t means that developer always write code newly, instead they use same existing code with additional required features only.
b) iPhone has different versions of mobile phones such as iPhone 13, iPhone 14, iPhone 15, etc.

Advantages of inheritance

1) Re-usability of code.
2) Save developers efforts and cost in terms of time.
3) Code maintainability

FAQs in Inheritance

1) What is Inheritance?
2) syntax of Inheritance?
3) How to achieve inheritance?
4) What are the types of inheritance?
5) Advantages of Inheritance
6) Example of inheritance

Thanks for visiting Ajitation.com, Ajitation is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.