What is Inheritance in Java and How to Implement It

One of the most widely used programming languages in the world, Java has many powerful features. Inheritance in Java is one of the core topics in OOPs concepts and Java. It enables developers to inherit data members and properties from one class to another.  

What Is inheritance in Java?

Inheritance is one of the object-oriented programming concepts in Java. Inheritance enables the acquisition of data members and properties from one class to another.

The components that make up the process of inheriting data members and properties is as follows:

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Base Class (Parent Class)

The base class provides the data members and methods in alternative words. Any base class that needs methods or data members will have to borrow them from their respective parent or base class.

Subclass (Child Class)

The subclass is also known as the child class. The implementation of its parent class recreates a new class, which is the child class. 

To inherit the parent class, a child class must include a keyword called "extends." The keyword "extends" enables the compiler to understand that the child class derives the functionalities and members of its parent class.

To understand this in an easier way, let us verify the syntax for inheritance in Java.

Syntax:

class SubClass extends ParentClass  
{  
//DataMembers;
//Methods;   
} 

The following program is a good example that better explains Java inheritance terminology.

Example:

Let’s say that Samsung wants to make a new washing machine and includes a method that activates gentle wash messages in the motor, while also saving time. To do so, we can write the code so that the machine can inherit the gentle wash method into its latest model.

//Inheritance Example
package inheritance;
class Machine {
protected String brand = "Samsung";
public void wash() {
System.out.println("Initiating Gentle-Wash Task");
}
}
public class WashingMachine extends Machine {
private String modelName = "Top Load Washing Machine";
public static void main(String[] args) {
WashingMachine washmachine = new WashingMachine();
washmachine.wash();
System.out.println(washmachine.brand + " - " + washmachine.modelName);
}
}

Why Do We Need Inheritance?  

The two main reasons we need inheritance include:

Run-Time Polymorphism

Runtime, also known as dynamic polymorphism, is a method call in the execution process that overrides a different method in the run time.  

Code Reusability 

The process of inheritance involves reusing the methods and data members defined in the parent class. Inheritance eliminates the need to write the same code in the child class—saving time as a result.

Next, we’ll cover the guiding principles for obtaining access to a parent class. The accessibility of a parent class is based on the access modifiers used

Access Modifiers

Access modifiers specify the availability of a parent class. In real-time coding, we cannot allow child classes to have access to all of the other classes. The availability of a data member, method, or constructor can be described in four ways.

Access_Modifiers_Inheritance_in_Java

Default

The default access modifier is a default option for providing accessibility to a class when it is not provided with any specific access modifier from the user. The default access specifier is similar to the public access modifier. The difference is that the parent class is only accessible inside the Java project's package that is currently in use, but not outside of the package.

Example:

package Simplilearn;  
class Parent{ 
void msg(){System.out.println("Hello World");} 
} 
package Simpli;  
import Simplilearn.*; 
class Child{  
public static void main(String args[]){  
Parent P = new Parent();
//Compile Time Error  
P.msg();//Compile Time Error  
}
}

Public

The public access modifier is used when the user wants all child classes to have access to the parent class from anywhere in the Java project, as well as any other packages.

Example:

//Public
package inheritance;
public class Summation 
{public int add(int x, int y)
{return x + y;
}
}
package inheritance2;
import inheritance.*;
public class Child {
public static void main(String args[])
{
Summation A = new Summation();
System.out.println(A.add(100, 200));
}
}

Protected

The protected access modifier is a little different from the others. This class is accessible to its child class only. If a user needs to access the protected data members and methods from a different class, accessing the protected class’s child class is the only way it can be done. 

Example:

//Protected
package inheritance;
public class Parent
{ 
protected void Print() 
{ 
System.out.println("Hello World");
} 
}
package inheritance2;
import inheritance.*;
public class Child extends Parent {
public static void main(String args[]) {
Child x = new Child();
x.Print();
}
}

Private

The private access modifier has strict rules for accessing private data members and methods. The private access specifier provides access within the class, but not outside of the class.

Example:

//Private
//Without Getter and Setter
//This program will have Compile-time error
package inheritance;
class Print {
private int value = 5;
private void Display() {
System.out.println("Hello World");
}
}
public class call {
public static void main(String args[]) {  
Print A =new Print();    
System.out.println(A.value);  
A.Display();
}
}
//With Getter and Setter
package inheritance;
class Print {
private int x = 5;
void Display() {
System.out.println("Hello World");
}
public int getX() {
return x;
}
public void setX(int x)
{
this.x = x;
}
}
public class call {
public static void main(String args[]) 
{
Print A = new Print();
System.out.println(A.getX());
A.Display();
}
}

Super Keyword

The super keyword is a unique keyword that refers to an immediate parent class's object. If you create an instance of the child class, then the super keyword implicitly refers to the parent class instance.

Example:

//Super Keyword
package inheritance;
class Jet {
int TopCruiseSpeed = 1800;
}
public class Su30MKI extends Jet {
int TopCruiseSpeed = 2500;
void Print() {
System.out.println("Maximum cruise Speed: " + super.TopCruiseSpeed);
}
}
class Takeoff {
public static void main(String[] args) {
Su30MKI Fighter = new Su30MKI();
Fighter.Print();
}
}

Types of Inheritance in Java

There are five types of inheritance in Java:

1) Single Inheritance
2) Multi-Level Inheritance
3) Hierarchical Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance

We will discuss each one of them in detail.

Single Inheritance

Single inheritance consists of one parent class and one child class. The child class inherits parent class methods and data members.

Single_Inheritance

Example:

//Single
package inheritance;
class Student {
void Play() {
System.out.println("Playing Fooball...");
}
}
class Bob extends Student {
void Study() {
System.out.println("Studing Physic...");
}
}
public class Single {
public static void main(String args[]) {
Bob d = new Bob();
d.Study();
d.Play();
}
}

Multi-Level Inheritance

Multi-level inheritance is like a parent-child inheritance relationship—the difference is that a child class inherits another child class.

/Multi-Level_Inheritance

Example:

//Multi-Level Inheritance
package inheritance;
class Bike {
public Bike() {
System.out.println("Segment: 1000cc");
}
public void BikeType() {
System.out.println("Bike Type: Sports");
}
}
class NinJa extends Bike {
public NinJa() 
{
System.out.println("Make NinJa");  
}
public void brand() {
System.out.println("Manufacturer: Kawasaki");
}
public void speed() {
System.out.println("Max Speed: 290Kmph");
}
}
public class NinJa1000R extends NinJa {
public NinJa1000R() {
System.out.println("NinJa Model: 1000R");
}
public void speed() {
System.out.println("Max Speed: 280Kmph");
}
public static void main(String args[]) {
NinJa1000R obj = new NinJa1000R();
obj.BikeType();
obj.brand();
obj.speed();
}
}

Hierarchical Inheritance

Hierarchical inheritance is a parent-child relationship. The only difference is that multiple child classes inherit one parent class.

Hierarchial_Inheritance-Inheritance_in_Java

Example:

//Hierarchical Inheritance
package inheritance;
class Employee {
double leaves = 25.00;
}
class PEmployee extends Employee {
float totalHoursPerDay = (float) 8.00;
}
class TEmployee extends Employee {
float totalHoursPerDay = (float) 10.50;
}
public class EmployeeSalary {
public static void main(String args[]) {
PEmployee permenant = new PEmployee();
TEmployee temporary = new TEmployee();
System.out.println("Permanent Employee Total Number of leaves are :\n" + permenant.leaves);
System.out.println("Number of working hours for Permanent Employee are:\n" + permenant.totalHoursPerDay);
System.out.println("Temporary Employee Total Number of leaves are :\n" + temporary.leaves);
System.out.println("Number of working hours for Temporary Employee are :\n" + temporary.totalHoursPerDay);
}
}

Hybrid Inheritance

Hybrid inheritance can be a combination of any of the three types of inheritances supported in Java.

/Hybrid_Inheritance-Inheritance

Example:

//Hybrid Inheritance
package inheritance;
class C {
public void Print() {
System.out.println("C is the Parent Class to all A,B,D");
}
}
class A extends C {
public void Print() {
System.out.println("A has Single Inheritance with C and shares Hierarchy with B");
}
}
class B extends C {
public void Print() {
System.out.println("B has Single Inheritance with C and shares Hierarchy with A");
}
}
public class D extends A {
public void Print() {
System.out.println("D has Single Inheritance with A and Multi-Level inheritance with C");
}
public static void main(String args[]) {
A w = new A();
B x = new B();
C y = new C();
D z = new D();
y.Print();
w.Print();
x.Print();
z.Print();
}
}
public class D extends A {
public void Print() {
System.out.println("D has Single Inheritance with A and Multi-Level inheritance with C");
}
public static void main(String args[]) {
A w = new A();
B x = new B();
C y = new C();
D z = new D();
y.Print();
w.Print();
x.Print();
z.Print();
}
}

Multiple Inheritance

There is also a fifth type of Inheritance, but it is not supported in Java, as multiple class inheritance causes ambiguities. Multiple inheritance is also called a diamond problem. Hence, Java does not support multiple class inheritance.  

Diamond_Problem-Inheritance_

Is-a Relationship

When a class inherits methods and members from a different class, then the relation is said to be an is-a relationship. 

Example: Orange is-a fruit.

IS-A_Relation.

Example:

//IS-A Relation
package inheritance;
import java.util.*;
class Customer {
public String Name;
public String City;
Customer(String Name, String City) {
this.Name = Name;
this.City = City;
}
}
class Bank {
private final List<Customer> customers;
Bank(List<Customer> customers) {
this.customers = customers;
}
public List<Customer> TotalAccountsInBank() {
return customers;
}
}
public class IsARelation {
public static void main(String[] args) {
Customer C1 = new Customer("Raju", "Bangalore");
Customer C2 = new Customer("Shiva", "Hyderabad");
Customer C3 = new Customer("Sachin", "Mumbai");
Customer C4 = new Customer("Prashanth", "Vizag");
Customer C5 = new Customer("John", "Goa");
List<Customer> Customers = new ArrayList<Customer>();
Customers.add(C1);
Customers.add(C2);
Customers.add(C3);
Customers.add(C4);
Customers.add(C5);
Bank ABCBank = new Bank(Customers);
List<Customer> cust = ABCBank.TotalAccountsInBank();
for (Customer cst : cust) {
System.out.println("Name of the Customer : " + cst.Name + "\n" + "City : " + cst.City);
}
}
}

Has-a Relationship

When a class inherits an instance from a different class or an instance of its class, then the relationship is a has-a type.

Ex: Orange has-a citrus taste. 

HAS-A_Relation

Example:

//HAS-A Relation
package inheritance;
class School {
private String name;
School(String name) {
this.name = name;
}
public String SchoolName() {
return this.name;
}
}
class Student {
private String name;
Student(String name) {
this.name = name;
}
public String StudentName() {
return this.name;
}
}
public class HasARelation {
public static void main(String[] args) {
School schl = new School("St.John's School");
Student candidate = new Student("Tobey Marshall");
System.out.println(candidate.StudentName() + " is an Ex-Student of " + schl.SchoolName());
}
}

Advantages and Disadvantages of Inheritance 

Advantages

  • Java inheritance enables code reusability and saves time
  • Inheritance in Java provides the extensibility of inheriting parent class methods to the child class
  • With Java inheritance, the parent class method overriding the child class is possible

Disadvantages

  • The inherited methods lag in performance 
  • Some of the data members of the parent class may not be of any use—as a result, they waste memory
  • Inheritance causes strong coupling between parent and child classes. This means, either of the two (Parent class or Child class) become incapable of being used independent of each other.
Do you wish to become a Java Developer? Check out the Java Certification Training Course and get certified today.

Conclusion

So this brings us to the end of the concept of Inheritance in Java. By completing this tutorial, you have now explored the basics of inheritance in Java, including access modifiers, super keywords, and relationships. You now have the tools to build java applications with increased re-usability, a fundamental pillar of Java OOP(Object Oriented Programming).

Want to learn more about Java? and getting certified as a professional Java developer? Be sure to check out our Java training and certification program, which has been collectively created by some of the most experienced industry experts.

If you have any questions about Java inheritance, please feel free to ask them in the comments section, and we’ll have our experts answer them for you.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.