Inheritance in Java

Inheritance in Java with Examples

In this article, I am going to discuss Inheritance in Java with Examples. Please read our previous where we discussed Access Modifiers in Java with Examples. At the end of this article, you will understand the following pointers in detail.

  1. What is Inheritance in Java?
  2. Understanding the extends keyword in Java
  3. Types of Inheritance in Java
  4. Why Multiple Inheritance is not supported in Java using classes?
  5. Single, Multilevel & Hierarchical Inheritance in Java
  6. The Java Super Keyword
  7. When and where to call Super()?
  8. Can we use the super keyword in the static method?
  9. Advantages of Inheritance in Java
What is Inheritance in Java?

Inheritance is an integral part of Java OOPs which lets the properties of one class to be inherited by the other. For example, a child inherits the traits of his/her parents. Inheritance is a programming construct that software developers use to establish is-a relationships between categories.

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Inheritance means establishing a logical relationship between two classes. In other words, inheritance means extending class functionalities (code reusing). Here, Relationship is categorized into two types:

  1. Is-a relationship
  2. Has-a relationship

What is Inheritance in Java?

Important Terminology in Inheritance:

Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.

Super Class: The class whose features are inherited is known as a superclass. The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.

Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

Extends keyword in Java:

In Java, using the “extends” keyword we can implement features programmatically. The Extends keyword establishes the is-a relationship between the classes. extends is the keyword used to inherit the properties of a class.

Syntax:

Extends keyword in Java:

In the below code snippet

Inheritance in Java with Real-time Examples

Here, class A is known as Base class or superclass or parent class and class B is known as derived/sub/child class. In the above snippet, class B contains additionally all the members of A (i.e.: because of is-a relationship).

Types of Inheritance in Java:

Supported types of Inheritance in Java are as follows:

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance

Note: Comparing to C++, Java does not support multiple inheritances directly. Individually, multiple inheritances are supported in Java using interfaces concept.

Why Multiple Inheritance is not supported in Java using classes?

Multiple Inheritance means creating a derived by extending multiple base classes at a time. Assume in below code snippet

Why Multiple Inheritance is not supported in Java using classes?

In this case, the compiler goes in an ambiguous state, because multiple base classes contain the same method name. In C++, we can handle this ambiguous problem using colon (::) operator syntax & syntactically it is not supported because Java follows dynamic loading procedure for non-static members (i.e.: we must use references to access that members)

Single Inheritance in Java:

Single Inheritance means creating a subclass to extend only one superclass at a time. In the diagram given below, class B inherits class A, so there is single inheritance.

Single Inheritance in Java

Sample Program of Single Inheritance:
package Demo;
class A
{
 int returnSum(int i, int j)
 {
  return i+j;
 }
}
class B extends A
{
 void display()
 {
  int result = returnSum(10,20);
  System.out.println(result);
 }
}
public class SingleInheritance {
 public static void main(String args[])
 {
  B b1 = new B();
  b1.display();
  b1=null;
 }
}

Output: 30

In Java, whenever in the object creation of subclass, internally. JVM creates an object of the superclass. Because of tight coupling & JVM maintains superclass object copy into the subclass object. So once the subclass object becomes unreachable internally superclass object is also garbage collected.

In case of accessing always first priority is given to subclass members whereas, in case of object creation, the first priority is given to superclass and next to subclass.

Multilevel Inheritance in Java:

Creating a subclass (derived class) indirectly to the superclass is known as multilevel inheritance. As you can see below in the diagram, class C inherits class B which again inherits class A, so there is a multilevel inheritance.

Multilevel Inheritance in Java

Sample Program of Multilevel Inheritance:
package Demo;
class SampleA
{
 void f1()
 {
  System.out.println("class A f1()");
 }
}
class SampleB extends SampleA
{
 void f2()
 {
  System.out.println("class B f2()");
 }
}
class SampleC extends SampleB
{
 void f3()
 {
  System.out.println("class C f3()");
 }
}
public class MultilevelInheritance {
 public static void main(String srgs[])
 {
  SampleC a1 = new SampleC();
  a1.f1();
  a1.f2();
  a1.f3();
  a1 = null;
 }
}

Output:

Sample Program of Multilevel Inheritance

Hierarchical Inheritance in Java:

When two or more classes inherit a single class, it is known as hierarchical inheritance. In the diagram given below, B and C classes inherit class A, so there is hierarchical inheritance.

Hierarchical Inheritance in Java

Sample Program of Hierarchical Inheritance:
package Demo;
  
class one 
{ 
    public void print_hello() 
    { 
        System.out.println("Hello"); 
    } 
} 
  
class two extends one 
{ 
    public void print_world() 
    { 
        System.out.println("World"); 
    } 
} 
  
class three extends one 
{ 
    /*............*/
} 
  
// Drived class 
public class HierarchicalInheritance 
{ 
    public static void main(String[] args) 
    { 
        three g = new three(); 
        g.print_hello(); 
        two t = new two(); 
        t.print_world(); 
        g.print_hello(); 
    } 
}

Output :

Sample Program of Hierarchical Inheritance

The Java Super Keyword:

The super keyword is similar to this keyword. The keyword super can be used to access any data member or methods of the parent class. The super keyword can be used at variable, method, and constructor level.

Following are the scenarios where the super keyword is used:

  • To access the superclass variable from a subclass.
  • To access the superclass methods from a subclass.
  • To access the superclass constructor from a subclass.

Syntax of super(): super. <method_name> ();

When and where to call Super()?

Just as this() must be the first element in a constructor that calls another constructor in the same class, super() must be the first element in a constructor that calls a constructor in its superclass. If you break this rule the compiler will report an error. The compiler will also report an error if it detects a super() call in a method; only ever call super() in a constructor.

Example of Inheritance using Super Keyword:
package Demo;
class Father
{
 int bank_balance = 500000;
}
class Daughter extends Father
{
 int bank_balance = 300000;
 
 public void displayBalance()
 {
  System.out.println("Bank Balance : "+super.bank_balance);
 }
}
public class Inheritance {

 public static void main(String[] args) {
  Daughter d = new Daughter();
  d.displayBalance();
 }
}

Output: Bank Balance : 500000

Can we use the super keyword in the static method?

No, because static methods are loaded as soon as JVM creates a CONTEXT memory for the subclass but the super keyword is pointed to superclass object. In this case, the object is not created so that’s why we cannot access the super keyword in the static method.

The need for Inheritance :

The most important use is the reusability of code. The code that is present in the parent class doesn’t need to be written again in the child class. To achieve runtime polymorphism through method overriding.

What You Can Do in a Subclass?

You can use the inherited members as is, replace them, hide them, or supplement them with new members:

  • The inherited fields or methods can be used directly, just like any other field.
  • You can declare a field or methods and write a new static method in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
Rules of writing Inheritance:
  1. Multiple Inheritance is NOT permitted in Java using classes.
  2. Cyclic Inheritance is NOT permitted in Java.
  3. Private members do NOT get inherited.
  4. Constructors cannot be Inherited in Java.
  5. In Java, we assign parent reference to child objects.
  6. Constructors get executed because of super() present in the constructor.
Advantages of Inheritance in Java:
  • It reduces duplicate code (i.e.: define ones and use at anywhere(Java slogan))
  • It provides code re-usability support.
  • It increases the maintenance of the Application.
  • It reduces application development time.

In the next article, I am going to discuss Abstraction in Java with examples. Here, in this article, I try to explain Inheritance in Java with Examples. I hope you enjoy this Inheritance in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *