×

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

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.