Inheritance in Java with Example


< Previous Next >

OOPS Tutorial


In this article, we will learn Inheritance in Java with real-time examples and source code examples.

We will learn what is Inheritance and the types of Inheritance with examples.

1. Intent/Definition

Inheritance - IS-A relationship between a superclass and its subclasses.

The Inheritance is a process of obtaining the data members and methods from one class to another class, plus can have its own is known as inheritance. It is one of the fundamental features of object-oriented programming.

Important terminology: 

Super Class: The class whose features are inherited is known as a superclass (or a base class or a parent class).
Sub Class: The class that inherits the other class is known as a 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.

When we say that class B is inherited from another class A, then class B is referred to as a subclass (or derived class) and class A is called superclass (or base class).

2. Inheritance Real-World Example

  1. The real-life example of inheritance is child and parents, all the properties of a father are inherited by his son.
  2. In the Java library, you can see extensive use of inheritance. The below figure shows an inheritance hierarchy from java.lang library. The Number class abstracts various numerical (reference) types such as Byte, Integer, Float, Double, Short, and BigDecimal.

3. Implementation with Examples

Example 1: Let's understand inheritance by example.
Dog class is inheriting behavior and properties of Animal class and can have its own too.
/**
 * Test class for inheritance behavior - Dog class is inheriting behavior 
 * and properties of Animal class and can have its own too.
 * 
 * 
 */
public class Inheritance {

    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.setId(123); // inherited from super class
        dog.sound(); // overrided behavior of sub class
    }
}

/**
 * This is parent (also called as super or base) class Animal
 *  
 */
class Animal {
    int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void sound() {
        System.out.println("By default it is mute");
    }
}

/**
 * This is subclass (also called as derived or child or extended) Dog which is extending Animal
 * 
 */
class Dog extends Animal {
 
    // Own behavior
    private void bark() {
        System.out.println("Dog '" + getId() + "' is barking");
    }

    // Overriding super class behavior
    @Override
    public void sound() {
        bark();
    }
}
The keyword used for inheritance - extends.
Syntax :
class derived-class extends base-class  
{  
   //methods and fields  
} 
Example 2: In this example, the Programmer is the subclass and the Employee is the superclass. The relationship between the two classes is the Programmer IS-A Employee. It means that a Programmer is a type of Employee.
class Employee{  
    float salary=40000;  
}  
class Programmer extends Employee{  
    int bonus=10000;  
    public static void main(String args[]){  
        Programmer p=new Programmer();  
        System.out.println("Programmer salary is:"+p.salary);  
        System.out.println("Bonus of Programmer is:"+p.bonus);  
    }  
}  

4. Types of Inheritance in Java

Below are the different types of inheritance which are supported by Java.

4.1 Single Inheritance

In single inheritance, subclasses inherit the features of one superclass. 

In the image below, class A serves as a base class for the derived class B.

4.2 Multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also act as the base class to other class. 

In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C

Note: In Java, a class cannot directly access the grand parent’s members.

4.3 Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived class B and class C.

4.4 Multiple Inheritance (Through Interfaces)

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. 

Please note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces. 

In the image below, Class C is derived from class A and class B.

4.5 Hybrid Inheritance(Through Interfaces)

It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with classes. 

In java, we can achieve hybrid inheritance only through Interfaces.

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritances is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits the A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call a method of A or B class.
Since compile-time errors are better than runtime errors, java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile-time error now.
class A{  
    void msg(){System.out.println("Hello");}  
}  
class B{  
    void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
   
     Public Static void main(String args[]){  
          C obj=new C();  
          obj.msg();//Now which msg() method would be invoked?  
     }  
}

GitHub Repository 

The source code of this article is available on my GitHub repository at OOPS Concepts Tutorial.
Learn complete Java Programming with Examples - Java Tutorial | Learn and Master in Java Programming with Examples

Related OOP Posts

Comments