×

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes a relationship between different classes. It is an essential part of oops (object-oriented programming system). As we know in real life, a son inherits the properties from his father just like that inheritance acts in Java. Java follows the similar concepts of son and father relationship. Java inheritance represents a parent-child relationship which is also known as IS-A relationship. Java has two classes
  • Parent class / Superclass / Base class
  • Child class/ Subclass /Derived class
A class whose properties are inherited is known as parent class whereas a class which inherits is known as Child class. Java uses the ‘extends’ keyword to inherit the attributes and methods from a class. Let’s have a look on the following example
class Teacher{
String prof = "Teacher";
String col_n = "IIT K";
void does(){
System.out.println("Teaching");
}
}
 public class CSTeacher extends Teacher{
     String sub = "Java";
     public static void main(String args[]){
     CSTeacher z = new CSTeacher();
     System.out.println(z.col_n);
     System.out.println(z.prof);
     System.out.println(z.sub);
     z.does();
       }
       }
Output
IIT K
Teacher
Java
Teaching
In the above example, the Child class CSTeacher holds the attributes and methods of parent class Teacher like designation, collegeName and void does(). The extends keyword indicates that you are using properties in a new class that derives from an existing class.

Advantage of Inheritance

  • Inheritance helps to achieve runtime polymorphism for method overloading.
  • Inheritance facilitates with code reusability.
  • Inheritance decreases the line of codes in Java program.
  • Inheritance minimizes the amount of duplicate code by sharing the standard code amongst several subclasses.
  • Inheritance facilitates with data hiding feature. The base class can decide to keep some data private so that the derived class can not alter it.

Disadvantage of Inheritance

The main disadvantage of inheritance is that two classes (base and derived) are tightly coupled that it cannot be used independently of each other. Another disadvantage of the inheritance is that it increases time/ effort it takes the program through all levels of overloaded class.

Types of inheritance in Java

Different types of inheritance supported by Java are as follows.
  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical inheritance

Single inheritance

In single inheritance, one class inherits only another class. In the given figure, Class A is parent class, and Class B is Child Class, and class B is inheriting the properties and behavior. This process is known as single inheritance. Example
public class A
{
  public void print1()
  {
      System.out.println("Class A method");
  }
}
class B extends A
{
  public void print2()
  {
      System.out.println("Class B method");
  }
  public static void main(String[] args)
  {
      B d = new B();
      d.print1();
      d.print2();
      d.print1();
  } }
Output
Class A method
Class B method
Class A method 

Multilevel inheritance

In multilevel inheritance, a child class will be inheriting a parent class as well as the child class, and also parent class for some other class. In the given diagram, class A serves as a parent class for the class B., and also class B serves as a parent class for class C. This process is known as multilevel inheritance. A class can’t access directly inherit the grandparent class.
public class A
{
  public void print1()
  {
      System.out.println("Class A method");
  }
}
class B extends A
{
  public void print2()
  {
      System.out.println("Class B method");
  }
  }
class C extends B
{
    public void print3()
    {
        System.out.println("Class C method");
    }
public static void main(String[] args)
{
    C d = new C();
    d.print1();
    d.print2();
    d.print3();
}}
Output
Class A method
Class B method
Class C method

Hierarchical inheritance

In hierarchical inheritance, a single base class serves many sub classes. More than one child classes can inherit the properties of the parent class. In the given figure, Class B, Class C, and class D are the subclasses of Class A.

java hierarchical inheritance Example

class A
{
    public void print1()
    {
        System.out.println("Class A method");
    }
}
class B extends A
{
    public void print2()
    {
        System.out.println("Class B Method");
    }
}
class C extends A
{
     public void print3()
     {
          System.out.println("Class C method");
     }
}
public class Main
{
    public static void main(String[] args)
    {
        C d = new C();
        d.print1();
        B b = new B();
        b.print2();
        d.print3();
    }
}
Output
Class A method
Class B Method
Class C method

Super keyword in Java inheritance

In Java, the keyword ‘super’ and ‘this’ are very similar. Super keyword refers to the object of the base (parent) class. It acts as a reference variable. Super can be used in the following context.
  • Use of super with variables
  • Use of super with methods
  • Use of super with constructors

Some scenarios with the super keyword

Let’s see an example to understand the super keyword.   Example 1
class ParentClass
{
 int n = 50;
}
class ChildClass extends ParentClass
{
  int n = 80;
  void printNumber(){
     System.out.println(n);
  }
  public static void main(String args[]){
     ChildClass obj= new ChildClass();
     obj.printNumber();
  }
}
Output
80
In the given example, we have avoided the use of the super keyword. Now see the example with super keyword.
class ParentClass
{
 int n = 50;
}
class ChildClass extends ParentClass
{
  int n = 80;
  void printNumber(){
     System.out.println(super.n);
  }
  public static void main(String args[]){
     ChildClass obj= new ChildClass();
     obj.printNumber();
  }
}
Output
50
In the given example, when we use the super keyword then it refers the parent class object. Example 2 Let’s understand how super keyword acts with parent class constructor.
class ParentClass
{
    ParentClass()
    {
        System.out.println("Parent class Constructor");
    }
}
class ChildClass extends ParentClass
{
    ChildClass()
    {
        super(); //invoke super class constructor
        System.out.println("Child class Constructor");
    }
}
class SuperDemo
{
    public static void main(String[] args)
    {
        ChildClass c = new ChildClass();
    }
}
Output
Parent class Constructor
Child class Constructor
This is an example of use of super keyword with constructor.

Question: Does Java supports multiple inheritance, explain?

Answer Java doesn't support multiple inheritance through classes, but It can be achieved through interfaces. It has some conflict like the diamond problem that is why java developers excluded this feature from java. Some other languages like c++, common lisp support multiple inheritance, but java avoids it. It prevents multiple inheritance from avoiding ambiguity.

Question: Explain diamond problem in Java.

Answer: The diamond problem The following diagram and program will clear the image of the diamond problem.
class A
{
  void m1()
 {
System.out.println("class A");
}}
class B extends A
{
void m1()
{
System.out.println("Class B");
}
}
class C extends A
{
void m1()
{
 System.out.println("Class C");
}
}
class Test extends A, B
{
 public static void main(String args[])
 {
Test d1 = new Test();
 d1.m1();
 }
}
Output-
This program will produce compile time error.
As we can see in the above program on calling method m1() using D class object will cause complication. The program got confused whether it calls A's method m1() or B's method m1() because class D inheriting both class A and B. This complicated situation is called diamond problem.

← Prev Next →


Related Topics

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

8 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.