• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Introduction » Inheritance in Java
Next →
← Prev

Inheritance in Java

By Dinesh Thakur

The objects are the building blocks of the object oriented programming language. A programmer may use multiple objects belonging to different classes in some situations, which may have some relationship among themselves as they share some common features. 

Let us consider an example of a program containing objects of two different classes, Car and Motorcycle, for maintaining car and motorcycle information, respectively. Both Car and Motorcycle classes exhibit some relationship as both are vehicles and share some common features like speed, engine specification, etc. To represent the relationship between classes, we use the concept of Inheritance.

We’ll be covering the following topics in this tutorial:

  • What is Inheritance in Java
  • Advantage of Inheritance
  • Implementing Inheritance
  • Inheritance and Access Specifiers
  • Types of Inheritance in Java
  • What is the importance of Inheritance in java?

What is Inheritance in Java

Inheritance in Java is one of the compile-time mechanisms in the Object-Oriented Programming language, enabling you to organize classes in a hierarchical form. Just like a child inherits his parents’ characteristics and adds certain new characteristics of his own.  

A programmer can write a new class that can inherit the accessible fields and methods and may also add new fields and methods. The inclusion of members of the existing class in a new class so that they are accessible in the new class is known as class inheritance. 

The existing class that is being inherited is called the superclass, and the new class that inherits the functionality is called the subclass. In some other programming languages, a superclass can also be referred to as a parent, base class, or an ancestor, and the subclass is referred to as a child, derived class, or a descendant.

Advantage of Inheritance

The main advantage of Inheritance is the reusability of the code. Inheritance allows well-tested code to be reused and enables changes to be made once and affect all relevant places. Once the superclass has been written, tested, and debugged properly, its functionality can be reused by the subclasses rather than being rewritten from scratch. The subclass inherits the members of the superclass and can add members of its own. Thus, it reduces the amount of new code that must be designed, written, and tested each time a program is developed. It also saves time and increases the reliability of the program. 

The benefit of reusability is more visible in developing complex projects involving many programmers. Without Inheritance, programmers may spend most of their time rewriting code they have written many times before. But using the concept of Inheritance, the same code can be written only once in the superclass and can be reused by different programmers. In general, Inheritance provides the ability to extend an existing class to meet new requirements without affecting the original class in any way.

To illustrate the concept of Inheritance, let us consider the following diagram :

inheritance in java

In the above diagram, Class X contains member A and B. Later on, if a Class Y is to be added in the program which contains identical members A and B to that of Class X along with an additional member C, then instead of writing the code for members A and B again in Class Y, it is better to inherit these members from an already existing Class X and only add additional member C in it as shown in the figure. Thus by inheriting the common features of the superclass into the subclass, the size of the code is reduced. It also helps to ensure consistency as common features do not exist in several classes and therefore, only need to be modified or tested once. The Class X from which the features are inherited is called the superclass and the Class Y that inherits the features is called the subclass.

In Fig, the arrow pointing in the upward direction from Class Y to Class X indicates that the Class Y is derived from the subclass Class X.

Implementing Inheritance

Inheriting a superclass gives a subclass the ability to define only those aspects that differ from or extend the superclass’s functionality. The syntax for creating a subclass is simple. At the beginning of your class definition, use the extends keyword after the class name followed by the name class being extended (i.e.superclass ). A subclass can only inherit directly from one superclass. Unlike C++, Java does not support multiple inheritances.

class SubClassName extends SuperClassName {
  // Additional member declarations
}

Here, SubClassName is the subclass’s name, and SuperClassName is the superclass’s name whose members are inherited by the subclass. The extends keyword identifies that SuperClassName is the superclass for class SubClassName.

This keyword establishes an inheritance relationship between the two classes. The subclass body contains the member’s declaration for all the members that are not common to that of the superclass.
The member inherited in the subclass is a full member of that class and is freely accessible to any method in the class. When an object(s) of the subclass is instantiated, it will contain the members of its class and contain all the inherited members of the superclass from which it is derived.
To understand how a subclass is derived from the superclass, let us consider a program with a superclass named Base consisting of a data field num1 and a method baseShow(). Suppose you want to extend the functionality of Base by adding new members. For this, we create a subclass named Derived, which is derived from the Base. So it inherits all the accessible members of the Base. It also extends the functionality of the Base by adding its field num2 and methods product() and derivedShow(). These members are exclusive to the subclass and cannot be used by the object of the superclass.

// show the use of inheritance
// super class
class Base {
  int num1;
  void baseShow() {
    System.out.println("num1 = "+num1);
  }
}
//subclass of Base class
class Derived extends Base {
  int num2;
  void product(){
    System.out.println("Product = "+(num1 * num2));
  }
  void derivedShow(){
    System.out.println("num2 = "+num2);
  }
}
public class Main {
  public static void main(String[] args){
    Derived d =new Derived();
    d.num1 =20;
    d.baseShow();
    d.num2 =10;
    d.derivedShow();
    d.product();
  }
}

Output :

num1 = 20                                                                                                                              
num2 = 10                                                                                                                              
Product = 200

Here, class Base is the superclass, and the class Derived is its subclass. In the class header, ‘Derived extends Base’ means that the class Derived implicitly inherits the data fields and methods of class Base.

In other words, we can say that class Derived inherits the field num1 and the method baseShow () from the class Base. These members are freely accessible to any method of the class Derived as if they are members of that class. It can be seen in the method product () of the class ‘Derived,’ where the num1 field of class Base is referred to directly.
In the main() method, when the Derived object is created, it can access both num1 and num2 fields as well as can call methods baseShow(), derivedShow(), and product().

Derived object is createdInheritance and Access Specifiers

Inheritance is a mechanism of creating a new class from an existing class by inheriting the existing class’s features and adding additional features of its own.

When a class is derived from an existing class, all the superclass members are automatically inherited in the subclass. However, it is also possible to restrict access to the superclass’s fields and methods in the subclass. It is possible by applying the access specifiers to the member of the superclass. If you do not want a subclass to access a superclass member, give that member private access. The superclass’s private members remain private (accessible within the superclass only) in the superclass and hence are not accessible directly to the subclass members. However, the subclass can access them indirectly through the inherited accessible methods of the superclass.

Types of Inheritance in Java

Types of inheritance in javaSimple Inheritance

When a  subclass is derived simply from it’s parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it’s parent class. It is also called single inheritance or one level inheritance.

class A {
 int x;
 iny y;
 int get(int p,int q) {
   x = p;
   y = q;
   return(0);
 }
 void Show() {
   System.out.println(x);
 }
}
class B extends A {
 public static void main(String args[]) {
   A a = new A();
   a.get(5,6);
   a.Show();
 }
 void display() {
   System.out.println("B");
 }
}

Multilevel Inheritance

It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class, this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for its parent class, and this parent class works as the child class for it’s just above ( parent ) class. Multilevel inheritance can go up to any number of levels.

class A {
  int x;
  int y;
  int get(int p,int q) {
    x = p;
    y = q;
    return(0);
  }
  void Show() {
    System.out.println(x);
  }
}
class B extends A {
  void Showb() {
    System.out.println("B");
  }
}
class C extends B {
  void display () {
    System.out.println("C");
  }
 public static void main(String args[]) {
   A a = new A();
   a.get(5,6);
   a.Show();
 }
}

Hierarchical Inheritance

The existing class is inherited by one or more child classes (subclasses) then such kind of inheritance is known as hierarchical.

In the above program, Class B, C, and D are the subclasses that inherit the super class’s functionality, i.e., Class A.

class Shape {
 public void Shaped() {
  System.out.println("Base Class - Shape");
 }
}
class Rectangle extends Shape {
 public void Rectangled() {
   System.out.println("Derived Class - Rectangle");
 }
}
 class Triangle extends Shape {
 public void Triangled() {
   System.out.println("Derived Class - Triangle");
 }
 }
class Circle extends Shape {
 public void Circled() {
   System.out.println("Derived Class - Circle");
 }
}
 class JavaExample {
   public static void main(String args[]) {
    Rectangle Rect = new Rectangle();
    Triangle Tri = new Triangle();
    Circle Cir = new Circle();
   //All classes can access the method of class Shape
    Rect.Shaped();
    Tri.Shaped();
    Cir.Shaped();
  }
}

Hybrid Inheritance

It is the combination of two or more types of inheritance.

What is the importance of Inheritance in java?

• Code reusability: It is a fundamental feature of inheritance. It allows us to reuse code that already exists rather than repeatedly writing and creating identical codes. Not only does this save a great deal of time and money because the properties are reused, but it also makes our code a great deal more reliable.

• Method Overriding: When we use inheritance, we can override the methods in our base class, making the base class more comfortable to use in a derived class.

• When both a parent and a child class have identical data members, inheritance becomes known as data hiding.

• When both a parent and a child class have the same functions, inheritance becomes known as method overriding.

• When both a parent and a child class have the same static functions, inheritance becomes known as function hiding.

• You cannot print the super keyword; if you tried, you would get a syntax error. The child class uses the super keyword to inherit the data members of a parent class.

• If a non-static function is made as final in any class, the child class might not override it.

You’ll also like:

  1. Example of Inheritance in Java
  2. Implementing Inheritance in Java Example
  3. Multilevel Inheritance in Java Example
  4. Single Inheritance in Java Example
  5. Example of Multilevel Inheritance in Java
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW