×

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

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.