Inheritance in Java with Example


< Previous Next >

OOPS Tutorial


1. Overview

In this article, we will learn the important object-oriented concept Inheritance
Inheritance - IS-A relationship between a superclass and its subclasses.
We will learn what is Inheritance and types of Inheritance with examples.

2. 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).

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. Below figure shows a partial inheritance hierarchy from a java.lang library. The Number class abstracts various numerical (reference) types such as Byte, Integer, Float, Double, Short, and BigDecimal.

3. Implementation

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 isextends.
Syntax :
class derived-class extends base-class  
{  
   //methods and fields  
} 
Example 2: In this example, the Programmer is the subclass and Employee is the superclass. The relationship between the two classes is the Programmer IS-A Employee. It means that 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 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. 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 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, the 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 inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits 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 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 available on my GitHub repository at OOPS Concepts Tutorial.

Learn complete Java Programming with Examples

Related Oops Posts

Top Core Java Tutorials

  1. Java Tutorial for Beginners
  2. 50 Java Keywords
  3. JDBC 4.2 Tutorial
  4. All Java/J2EE Tutorial
  5. Java 8 Tutorial
  6. Java Collections Tutorial
  7. Java Exceptions Tutorial
  8. Java Generics Tutorial
  9. Java 8 Stream API Tutorial
  10. Java Wrapper Classes
  11. Java Arrays Guide
  12. Java Multithreading Tutorial
  13. Java Concurrency Tutorial
  14. Oops Concepts Tutorial
  15. Java String API Guide
  16. Java Reflection API Tutorial
  17. Java I/O Tutorial
  18. Date and Time API Tutorial
  19. JUnit 5 Tutorial
  20. JUnit 4 Tutorial
  21. Java XML Tutorial
  22. Google GSON Tutorial

Top Java EE Tutorials

  1. Spring Security Tutorial
  2. RabbitMQ Tutorial
  3. Hibernate ORM 5
  4. Java Persistence API
  5. Spring Boot 2 Tutorial
  6. Spring Core 5 Tutorial
  7. Spring MVC 5 Tutorial
  8. Spring Data JPA Tutorial
  9. Apache HttpClient Tutorial
  10. Spring Framework 5
  11. Apache Maven Tutorial
  12. JAX-RS Tutorial
  13. Jersey Rest Tutorial

Java Library Tutorials

  1. Java API Guides
  2. Java SQL Package Tutorial
  3. All Java/J2EE Tutorial
  4. Java Lang Package Tutorial
  5. Java Util Package Tutorial
  6. Java Lang Reflect Package Tutorial
  7. Java Time Package Tutorial
  8. Java IO Package Tutorial

Top Java Best Practices

  1. Java Enums and Annotations Best Practices
  2. Java Generics Best Practices
  3. JUnit Framework Best Practices
  4. Java Naming Conventions
  5. Single Responsibility Principle
  6. Liskov's Substitution Principle
  7. Interface Segregation Principle
  8. Dependency Inversion Principle
  9. Open Closed Principle
  10. Oops principles in java
  11. Restful API Best Practices
  12. JSP Best Practices
  13. Guide to JDBC Best Practices
  14. Collection Best Practices
  15. String Best Practices in Java
  16. Exception Handling Best Practices
  17. Synchronization Best Practices
  18. Guide to JDBC Best Practices
  19. Serialization Best Practices

 

Comments