Inheritance in Java

Inheritance in Java

5 mins read1.1K Views Comment
Updated on Nov 23, 2023 14:24 IST

Delve into the world of Java inheritance, discovering the "IS A" relationship between classes, superclass and subclass dynamics, and the nuances of method overriding. Understand how Java leverages inheritance for versatile code structures and efficient polymorphism.

2022_06_1.jpg

Inheritance in Java is used to define the “IS A” relationship between two entities. For instance, a Banana IS A Fruit, a Dog is an Animal, Bike IS A vehicle, etc. In the above example, a banana acquires fruit properties through inheritance. However, the reverse is not true. 

What is Inheritance in Java?

Inheritance in Java means one entity acquiring properties or attributes of another entity. Java establishes inheritance between two classes using extends keyword. The class whose attributes are inherited is called a superclass or a parent class. Whereas, the class which inherits the properties is called a subclass or child class. As per the above example, Fruit is a superclass, and Banana is a subclass. 

Another example of inheritance is subclass Seed_Fruits inherits superclass Fruits.

image1

Compare and learn: Explore Best Java Course

Inheritance and Member Access

As we know about Access Modifiers in Java, a class can have members as public, private, protected, and default (package-level) numbers. However, during the inheritance process, these members behave differently as per their access levels.

Superclass Members Availability/Visibility in Subclass
Private Not Visible
Public Visible
Protected Visible
Default (Package-level) Visible only in same package

Example:

 


 
class A
{
private int a;
void setA()
{
a = 5;
}
}
class B extends A
{
public int b = 7;
void setB()
{
b = b*5;
}
}
class Main {
public static void main(String[] args) {
B b = new B();
b.setA(); //valid
System.out.println("a = " +b.a); //error!!!
b.setB(); //valid
System.out.println("b = " +b.b); //valid
}
}
Copy code

Explanation:

The methods setA() and setB() are default access levels and therefore are available in the Main class. However, the instance variable ‘a’ does not get inherited in class B as it is a private member of class A. Whereas, the instance variable ‘b’ being a public member is visible outside the class also in the main method.

Output:

output1

Also, Read: This keyword in Java

Relationship between a Superclass and Subclass

The subclass is a type or a specialization of a superclass. For instance, Dog IS AN Animal which implies that a subclass reference is also a type of superclass reference variable and hence can be assigned to a superclass variable.

However, vice versa is not possible as not all animals are dogs. Let’s take an example to understand this concept better.

Types of Inheritance in Java

There are several types of inheritance supported in Java which as given below:

Single Inheritance

The inheritance in which there exists one superclass (or parent class) and one subclass (or child class).

single

Example:

 


 
class A
{
int a = 5;
void inheritMe()
{
System.out.println("Hi! I just got inherited by class B");
}
}
class B extends A
{
int b = 7;
void bMethod()
{
System.out.println("Hi! I'm a class B method");
}
}
class Main {
public static void main(String[] args) {
B b = new B();
System.out.println("a = " +b.a);
System.out.println("b = " +b.b);
b.inheritMe(); //inherited from class A
b.bMethod();
}
}
Copy code

Explanation:

The above code shows how members of the superclass A gets inherited in the subclass B. The extends keyword is used to inherit class A to class B. Hence, class B can use the properties of class A.

Output:

output2

Multilevel Inheritance

The inheritance in which we have multiple levels of single inheritances is called a Multilevel Inheritance.

mutilevel

Example:


 
class Figure
{
double d1, d2; //Declaring Dimensions
Figure(double dim1, double dim2) //superclass (Figure) constructor
{
d1 = dim1;
d2 = dim2;
}
double calculateArea()
{
return d1*d2;
}
}
class Rectangle extends Figure
{
Rectangle(double l, double b) //Subclass (Rectangle) constructor
{
super(l,b); //calling superclass Figure constructor
}
}
class Square extends Rectangle
{
Square(double s) //Subclass (Square) constructor
{
super(s,s); //calling superclass Rectangle constructor
}
}
class Main1
{
public static void main(String[] args)
{
Rectangle r = new Rectangle(5,8);
System.out.println("Area of Rectangle: " +r.calculateArea());
Square sq = new Square(5);
System.out.println("Area of Square: " +sq.calculateArea());
}
}
Copy code

Explanation:

The square constructor calls the Rectangle constructor with the help of the super keyword which further calls the class Figure constructor initializing the instance variable and thus calculating the area.

Output:

output3
 

Hierarchical Inheritance

It is a type of inheritance where a superclass can have more than a subclass (or child class).

Hierarchical

Example:


 
class Figure
{
double d1, d2; //Declaring Dimensions
Figure(double dim1, double dim2) //superclass (Figure) constructor
{
d1 = dim1;
d2 = dim2;
}
double calculateArea()
{
return d1*d2;
}
}
class Rectangle extends Figure
{
Rectangle(double l, double b) //Subclass (Rectangle) constructor
{
super(l,b); //calling superclass Figure constructor
}
}
class Triangle extends Figure
{
Triangle(double b, double h) //Subclass (Triangle) constructor
{
super(b,h); //calling superclass Figure constructor
}
}
class Main1
{
public static void main(String[] args)
{
Rectangle r = new Rectangle(5,8);
System.out.println("Rectangle's Length: " +r.d1 + " Rectangle's breadth: " +r.d2);
System.out.println("Area of Rectangle: " +r.calculateArea());
Triangle t = new Triangle(4,3);
System.out.println("Triangle's base: " +t.d1 + " Triangle's height: " +t.d2);
System.out.println("Area of Triangle: " +t.calculateArea());
}
}
Copy code

Explanation:

The child class Rectangle and Triangle using the super keyword can access the variables of a parent class Figure. In this case, variables d1 and d2 of the Figure class are used by the Rectangle and Triangle class.

Output:

output4

Note: Java does not support multiple and hybrid inheritance. Instead, it uses Interfaces in Java to achieve this functionality.

Method Overriding

Method Overriding in Java undergoes the concepts of Inheritance and Runtime or Dynamic Polymorphism in Java. It is a process of redefining a superclass method with the same name, data types, and parameters in a subclass.

For more information, Read: Method Overriding in Java

 

Difference between Abstract class and Interface in Java
Difference between Abstract class and Interface in Java
Both abstract class and interface in java helps in achieving abstraction. They are similar in nature yet differ from each other when it comes to their usage. Let’s see what...read more
What is Wrapper Class in Java?
What is Wrapper Class in Java?
This article will teach you what is wrapper class and how wrapper objects are created. It will also teach you the concept of autoboxing and unboxing in java.
Multithreading in Java
Multithreading in Java
The below article goes through explaining the concepts of Multithreading in Java and its implementation. Let’s begin the tutorial.

Super keyword in Java

The super keyword in Java helps subclasses (or child classes) to access members (data members, methods, and constructors) of the superclass (or parent class) directly. In short, it’s a keyword that is used to access parent class objects. 

For more information, Read: Super Keyword in Java

Abstract Classes and Methods

Another concept in Inheritance is Abstract classes and methods in Java.

An abstract class is a class that may or may not contain some abstract methods. An abstract method is a method that does not have any definition. It is the responsibility of the subclass methods to give a concrete implementation of such methods. In doing so, each subclass is free to give its own implementation of the abstract method.

For more information, Read: Abstract Class in Java

Final Keyword in Java

Here’s another essential keyword in the concept of Inheritance in Java. The Final Keyword allows declaring a class, data members, and method to be unalterable. It’s generally used as an access modifier in Java for members.

For more information, Read: Final Keyword in Java

In Conclusion 

Hope the above article helped you build an understanding of the Inheritance in Java and its implementation ways. If you have any queries, feel free to reach out to us at the link below, and stay tuned for more java articles.

For more, Read: 8 Most Important Data Structures a Programmer Must Know

Blogs people also read in Java:

Data Type in Java | Features of Java Programming | Jump Statement in Java | OOPS in Java Java Interview Questions | Python vs Java | Conditional Statement in Java | Data Abstraction in Java | Super Keyword in Java | Method Overloading in Java | Array in Java | Difference between Java and Javascript | Constructors in Java | Method Overriding in Java Data Structure and Algorithm in Java | Abstract class in Java | Loops in Java

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio