INHERITANCE IN JAVA

Inheritance in Java is the capability of one class to inherit the capabilities or properties from other class. It helps in code usabilty, which is one of the most important feature of Object Oriented Programming. So, before we start our Inheritance tutorial, I recommend that you check the Java class concept.

Table of Contents

[hide]
  • What is Inheritance in Java
  • Need for Inheritance in Java
  • Types of Inheritance in Java

What is Inheritance in Java

Inheritance in Java is the mechanism in which ancestors (superclasses) inherit properties. Inheritance in Java can be defined as a mechanism where a new class (subclass) derives from properties of an existing class(superclass).

The concept behind Inheritance in Java is that you should be able to build new classes based on existing classes. After inheriting from an existing class, you can reuse parent class methods and fields. You can additionally add new methods and fields to the existing class as well.

The Java inheritance is declared using the Extends keyword. By using the keyword in the class description, you can declare that one class extends another class

Syntax : Java Inheritance

 class Subclass-name extends Superclass-name  
     .
     .
    //methods and fields  
 }

NOTE : extends keyword used for Class to Class relationship.

Inheritance is one of the main features of OOP (Object-oriented Programming)

Important Keyterms in Java Inheritance

Super Class

The class whose properties and functionalities are inherited by another class is known as super class(or a base class or a parent class)

Sub Class

A class that extends the characteristics of another class is known as a child class,a subclass or a derived class.

The extends keyword

The keyword extends implies that you are creating a new class which is derived from an existing class. The meaning of the term extends is to increase the functionality.

Let's take the example of humans, we inherit from the class of humans certain properties such as drinking, speaking, walking, bathing, etc. But these properties are not general to humans, the class of humans inherits these properties from a class called Mammal, which again inherits another class of Animals.

Lets take another example of a class Child which inherits certain properties from a class called Father, which again inherit from another class GrandFather.

Now let us learn from the simple example how inheritance works in Java.

Example :Inheritance in Java

copyimage
//Java Program to demonstrate the use of inheritance in Java
class SuperClass { 
   String name="Learn Inheritance with Examples";
   
   public void method1() {
	System.out.println("Inside Super Class or Parent Class Method");
   }
}
public class SubClass extends SuperClass  { 
    public void method2() {
        System.out.println("Inside Sub Class or Child Class Method");
    }

    public static void main(String[] args) {
    	SubClass obj=new SubClass();
    	obj.method2();
    	obj.method1();
    	System.out.println(obj.name);
    }
}

OUTPUT :

Inside Sub Class or Child Class MethodInside Super Class or Parent Class Method Learn Inheritance with Examples 

In the example given above we have a Super Class with a instance variable and a method. We created a SubClass that inherits the SuperClass properties using the extends keyword and define its own method2. Now with the use of extends keyword Child class or SubClass can access the public method1 of parent class.

inheritance in java

Need for Inheritance in Java

We use Inheritance in Java mainly for the following purposes :

  • It encourages reusability of the code, i.e. the same methods and variables specified in the parent / super / base class can be used in the child / sub / derived class.

  • It encourages polymorphism by allowing the method overriding..

  • Another reason for introducing the inheritance is for extendability purposes. Extending a class is simpler than writing a new class from scratch, and adding new functionality.

  • One of the use of inheritance promotes the maintainability of the code. Imagine that you've got a superclass and five subclasses. If you want to update a common feature of all these classes, you just need to update the parent class in one place. That's a lot easier than updating each class in case there's no inheritance.

  • In Java, when an ‘IS-A’ relationship occurs between the two classes we use inheritance.

Types of Inheritance in Java

There are five different types of Java Inheritance. Let’s discuss them one by one:

types of inheritance in java

In Object Oriented Programming, there are various forms of representing a Parent-Child relationship. Java supports different types of inheritance based on classes. Various types of inheritance are discussed further in this section and how they are realized using Java.

Single Inheritance In Java

This inheritance is the simplest type in Java and is a basic ONE to ONE relationship between two classes. We have already discussed the basic inheritance example in above section where a Child class inherits the properties of its Parent Class.

Single Inheritance in java

Lets take an example where we have a class "student" and we need to add a new class called "GraduateStudent". We derive the new class "GraduateStudent" from the existing class "Student" and then all we really need to add the extra features to "GraduateStudent" that describe the difference between students and graduate student.

Example : Single Inheritance in Java

copyimage
//Java Program to demonstrate the use of single inheritance in Java
class Student { 
    String name = "Virat Kohli";
    public void studentInfo() {
    System.out.println("GraduateStudent inheriting properties from Student");
  }
}
class GraduateStudent extends Student  { 
    String hobby = "Cricket";
    public void GraduateStudentInfo() {
    System.out.println("I am a Graduate Student who belong to Student Class");
  }
}
public class Codebator{
public static void main(String[] args) {
	GraduateStudent obj = new GraduateStudent();
	obj.GraduateStudentInfo();
	obj.studentInfo();
	System.out.println("Name of Graduate student : " + obj.name);
	System.out.println("Hobby : " + obj.hobby);
  }
}

OUTPUT :

I am a Graduate Student who belong to Student ClassGraduateStudent inheriting properties from Student Name of Graduate student : Virat Kohli Hobby : Cricket 

Multilevel Inheritance In Java

The child or derived class inherits the characteristics of the superclass in this form of inheritance and this child class concurrently serves as a superclass for another derived class.

Multilevel inheritance in java

With the continuation of the above example, now Employee class inherits properties from GraduateStudent Class, and GraduateStudent inherit properties from Student class. Its kind of a chain of inheritance.

Example : Multilevel Inheritance in Java

copyimage
//Java Program to demonstrate the use of Multilevel inheritance in Java
class Student {
   String name = "Virat Kohli";
   public void studentInfo() {
   System.out.println("GraduateStudent inheriting properties from Student");
  }
}

class GraduateStudent extends Student {
   String hobby = "Cricket";
   public void GraduateStudentInfo() {
   System.out.println("I am a Graduate Student who belong to Student Class");
  }
}

class Employee extends GraduateStudent {
   String company = "Google";
   public void EmployeeInfo() {
   System.out.println("I am a Employee inheriting properties from GraduateStudent");
  }
}

public class Codebator {
  public static void main(String[] args) {
     Employee obj = new Employee();
     obj.GraduateStudentInfo();
     obj.studentInfo();
     obj.EmployeeInfo();
     System.out.println("Name of Graduate student : " + obj.name);
     System.out.println("Hobby : " + obj.hobby);
     System.out.println("Company : " + obj.company);
    }
}

OUTPUT :

I am a Graduate Student who belong to Student ClassGraduateStudent inheriting properties from Student I am a Employee inheriting properties from GraduateStudent Name of Graduate student : Virat Kohli Hobby : Cricket Company : Google 

Hierarchical Inheritance In Java

When two or more classes inherit a single class, they are known as hierarchical inheritance. In Hierarchical Inheritance, one class is a superclass (base class) for more than one subclass. More than one subclass can inherit the basic class features.

Hybrid inheritance in java

In the continuation of above example, now both the classes i.e Employee and GraduateStudent will inherit the properties from Student class.

Example : Hierarchical Inheritance in Java

copyimage
//Java Program to demonstrate the use of Hierarchical inheritance in Java
//Base class
class Student {
    String name = "Virat Kohli";
    public void studentInfo() {
    System.out.println("I am a Student");
  }
}

//class 1
class GraduateStudent extends Student {
    String hobby = "Cricket";
    public void GraduateStudentInfo() {
    System.out.println("I am a Graduate who is a Student");
 }
}
//class 2
class Employee extends Student {
    String company = "Google";
    public void EmployeeInfo() {
    System.out.println("I am an Employee who is a Student");
 }
}

public class Codebator {
public static void main(String[] args) {
    Employee obj = new Employee();
    GraduateStudent obj2=new GraduateStudent();
    obj.studentInfo();
    // obj.GraduateStudentInfo(); //will give you error
    obj2.GraduateStudentInfo();
    obj.EmployeeInfo();
    System.out.println("Name of Graduate student : " + obj.name);
    System.out.println("Hobby : " + obj2.hobby);
    System.out.println("Company : " + obj.company);
  }
}

OUTPUT :

I am a StudentI am a Graduate who is a Student I am an Employee who is a Student Name of Graduate student : Virat Kohli Hobby : Cricket Company : Google 

Multiple Inheritance In Java

Java does not support multiple class inheritances. Multiple inheritances can only be achieved with the help of Interfaces.

Multiple inheritance in java

Why multiple inheritance is not supported in java?

Let us take the same above example of three classes i.e Student, GraduateStudent and Employee. The Employee class inherits Student and GraduateStudent classes. If Student and GraduateStudent classes have the same method and you call it from child class object, there will be ambiguity to call the method of student or GraduateStudent class.In order to avoid this ambiguity, Java does not allow multiple inheritances between classes and throws a compile-time error when multiple inheritance attempts are made.

Example : Multiple Inheritance in Java

copyimage
//Java Program to demonstrate the use of Multiple inheritance in Java
class Student {
    public void info() {
    System.out.println("I am a Student");
  }
}

class GraduateStudent {
    public void info() {
    System.out.println("I am a Graduate who is a Student");
  }
}

class Codebator extends Student,GraduateStudent { // if it would have been possible
 public static void main(String[] args) {
  	Codebator obj=new Codebator();
  	obj.info();//Now which info() method would be invoked? 
  }
}

OUTPUT :

Compile Time Error

Hybrid Inheritance In Java

Hybrid Inheritance In Java is a combination of two or more types of inheritance. It is also not possible in Java since Java does not support multipl inheritances with classes. Hybrid Inheritance In Java can only be achieved through Interfaces.

We will learn about multiple and Hybrid inheritance through interface in the upcoming tutorials.