Inheritance in Java

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class to be based on an existing class. The new class inherits the properties and methods of the existing class, known as the superclass or parent class. This concept promotes code reusability and helps in creating a hierarchical structure of classes. This article covers the definition, importance, key terminologies, types, examples, advantages, and disadvantages of inheritance in Java.

Contents:

  1. What is Inheritance?
  2. Importance of Java Inheritance
  3. Key Terminologies in Java Inheritance
  4. Types of Inheritance
  5. Java Inheritance Example
  6. Single Inheritance
  7. Multilevel Inheritance
  8. Hierarchical Inheritance
  9. Differences Between Inheritance Types in Java
  10. Advantages of Inheritance in Java
  11. Disadvantages of Inheritance in Java
  12. FAQs on Inheritance in Java

What is Inheritance?

Inheritance is the process where one class derives the attributes and behaviors of another. The class that inherits these properties and methods is known as the subclass or child class, while the class from which they are inherited is referred to as the superclass or parent class. The subclass not only inherits but can also augment with its own unique properties and methods, thus extending the functionality of the superclass.

Syntax:

class Superclass
{
    // fields and methods
}
 
class Subclass extends Superclass
{
    // additional fields and methods
}

advertisement
advertisement

Importance of Java Inheritance

Java inheritance is crucial because it:

  • Promotes Code Reusability: By inheriting properties and methods from existing classes, it reduces redundancy and promotes efficient code reuse.
  • Enables Method Overriding: Subclasses can provide specific implementations of methods defined in the superclass, enabling polymorphism.
  • Facilitates Extensibility: It allows adding new features to existing classes without modifying their structure, thereby enhancing flexibility and scalability.
  • Organizes Code Effectively: By creating hierarchical relationships between classes, it helps in structuring and organizing code, making it easier to manage and understand.

Key Terminologies in Java Inheritance

Understanding the following terminologies is essential for mastering inheritance in Java:

  • Class: A blueprint that defines the properties (fields) and behaviors (methods) of objects. In inheritance, classes form the foundation for creating a hierarchy.
  • Superclass: Also known as a parent class or base class, a superclass is a class from which other classes inherit properties and methods. It serves as the foundation for creating new classes.
  • Subclass: Also known as a child class or derived class, a subclass is a class that inherits properties and methods from a superclass. It extends the functionality of the superclass and can add new properties, methods, or override existing ones.
  • Extends keyword: In Java, the “extends” keyword establishes an inheritance relationship between a subclass and a superclass. It indicates that the subclass inherits from the specified superclass.
  • Constructor Chaining: Constructor chaining refers to the process of calling a constructor from another constructor within the same class or from a constructor in the superclass. This ensures proper initialization of the object.
  • Method Overriding: Method overriding occurs when a subclass provides its own implementation of a method that is already defined in the superclass. The overridden method in the subclass has the same signature (name, return type, and parameters) as the method in the superclass.
  • Access Modifiers: Access modifiers (e.g., public, private, protected) control the visibility and accessibility of classes, methods, and variables. They determine which members of a superclass are accessible to a subclass and other classes.

Types of Inheritance

Java supports four types of inheritance:

  1. Single Inheritance: In single inheritance, a subclass inherits from a single superclass. This is the most common type of inheritance in Java.
  2. Multilevel Inheritance: In multilevel inheritance, a subclass inherits from a superclass, which in turn inherits from another superclass. This creates a hierarchy of classes.
  3. Hierarchical Inheritance: In hierarchical inheritance, multiple subclasses inherit from a single superclass. This allows for the creation of a tree-like structure of classes.
  4. Multiple Inheritance: Java does not support multiple inheritance, where a subclass inherits from multiple superclasses. However, it can be achieved through the use of interfaces.

Java Inheritance Example

 
// Parent class
class Place
{
    protected String name;
    protected String location;
 
    public Place(String name, String location)
    {
        this.name = name;
        this.location = location;
    }
 
    public void displayInfo()
    {
        System.out.println("Name: " + name);
        System.out.println("Location: " + location);
    }
}
 
// Child class inheriting from Place
class Restaurant extends Place
{
    private String cuisineType;
 
    public Restaurant(String name, String location, String cuisineType)
    {
        super(name, location);
        this.cuisineType = cuisineType;
    }
 
    // Override displayInfo() to add cuisine type information
    @Override
    public void displayInfo()
    {
        super.displayInfo();
        System.out.println("Cuisine Type: " + cuisineType);
    }
}
 
// Main class
public class Main
{
    public static void main(String[] args)
    {
        Restaurant restaurant = new Restaurant("Italiano", "Main Street", "Italian");
 
        restaurant.displayInfo();
    }
}

This Java program demonstrates inheritance with a Place parent class and a Restaurant subclass. The Place class has attributes name and location, and a method displayInfo() to print these details. The Restaurant class inherits from Place and adds a cuisineType attribute. It overrides the displayInfo() method to include the cuisine type. In the Main class, an instance of Restaurant is created and its displayInfo() method is called, printing details such as the restaurant’s name, location, and cuisine type.

Output:

advertisement
Name: Italiano
Location: Main Street
Cuisine Type: Italian

This example showcases how inheritance allows subclasses like Restaurant to extend and specialize the behavior of their superclass, Place, by adding new attributes and overriding existing methods to fit their specific requirements.

Single Inheritance

Single inheritance in Java refers to the concept where a class can inherit variables and methods from only one superclass. In other words, a subclass can extend only one parent class.

Here’s a simple example to illustrate single inheritance:

advertisement
// Parent class (superclass)
class Person
{
    String name;
    int age;
 
    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
 
    public void displayInfo()
    {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
 
// Subclass (derived class)
class Student extends Person
{
    int rollNumber;
 
    public Student(String name, int age, int rollNumber)
    {
        // Call to superclass constructor
        super(name, age); 
        this.rollNumber = rollNumber;
    }
 
    public void displayStudent()
    {
        // Accessing superclass method
        displayInfo();  
        System.out.println("Roll Number: " + rollNumber);
    }
}
 
public class Main
{
    public static void main(String[] args)
    {
        Student student = new Student("Alice", 18, 1001);
        student.displayStudent();
    }
}

The provided Java program demonstrates single inheritance, where a Student class inherits from a Person superclass. The Person class defines two instance variables, name and age, which are initialized through its constructor. Additionally, it includes a method displayInfo() to print these details. The Student class extends Person and introduces an additional instance variable, rollNumber. Its constructor initializes the inherited name and age using super(name, age) and sets rollNumber to the provided value. The Student class also includes a method displayStudent() that first calls displayInfo() from the superclass to print the student’s name and age, and then prints the student’s roll number.

In the Main class, an instance of Student is created with the name “Alice”, age 18, and roll number 1001. When student.displayStudent() is called, it first prints:

Output:

Name: Alice
Age: 18

Followed by:

Roll Number: 1001

This output demonstrates how the Student class inherits from Person, utilizing the superclass’s attributes and methods, and extends its functionality by adding a specific attribute and method.

Multilevel Inheritance

Multilevel inheritance in object-oriented programming is when a class is derived from a class which is also derived from another class. This is achieved by creating a chain of inheritance among classes, where each subclass inherits characteristics and behavior from its parent class.

Example:
Here’s a example of multilevel inheritance in Java

// Base class
class A 
{
    void displayA()
    {
        System.out.println("A is displayed.");
    }
}
 
// Child class inheriting from A
class B extends A
{
    void displayB()
    {
        System.out.println("B is displayed.");
    }
}
 
// Grandchild class inheriting from B
class C extends B
{
    void displayC()
   {
        System.out.println("C is displayed.");
    }
}
 
// Main class to demonstrate the inheritance
public class Main
{
    public static void main(String[] args)
    {
        A objA = new A();
        objA.displayA();    
 
        B objB = new B();
        objB.displayA(); 
        objB.displayB();  
 
        C objC = new C();
        objC.displayA(); 
        objC.displayB(); 
        objC.displayC(); 
    }
}

Output:

A is displayed.
A is displayed.
B is displayed.
A is displayed.
B is displayed.
C is displayed.

In this Java example:

  • A is the base class with a method displayA.
  • B is a subclass of A that adds a method displayB and inherits the displayA method.
  • C is a subclass of B that adds a method displayC and inherits both displayA and displayB methods.

Each class inherits behavior from its parent class, and each subclass can extend and modify its parent’s behavior as needed. The output shows how methods from each class in the hierarchy are invoked and executed.

Hierarchical Inheritance

Hierarchical inheritance is a type of inheritance in object-oriented programming where one class serves as a superclass (base class) for multiple subclasses (derived classes). In this type of inheritance, each subclass inherits properties and behaviors from the same superclass independently, forming a hierarchical structure.

Example: Here’s a example of Hierarchical Inheritance in Java

// Employee class (base class)
class Employee
{
    private String name;
    private double salary;
 
    public Employee(String name, double salary)
    {
        this.name = name;
        this.salary = salary;
    }
 
    public String displayInfo()
    {
        return "Name: " + name + ", Salary: $" + salary;
    }
}
 
// Manager class (inherits from Employee)
class Manager extends Employee
{
    private String department;
 
    public Manager(String name, double salary, String department)
    {
        super(name, salary);
        this.department = department;
    }
 
    @Override
    public String displayInfo()
    {
        return "Manager - " + super.displayInfo() + ", Department: " + department;
    }
}
 
// Engineer class (inherits from Employee)
class Engineer extends Employee
{
    private String specialization;
 
    public Engineer(String name, double salary, String specialization)
    {
        super(name, salary);
        this.specialization = specialization;
    }
 
    @Override
    public String displayInfo()
    {
        return "Engineer - " + super.displayInfo() + ", Specialization: " + specialization;
    }
}
 
// Secretary class (inherits from Employee)
class Secretary extends Employee
{
    private String language;
 
    public Secretary(String name, double salary, String language)
    {
        super(name, salary);
        this.language = language;
    }
 
    @Override
    public String displayInfo()
    {
        return "Secretary - " + super.displayInfo() + ", Language: " + language;
    }
}
 
// Main class to test the inheritance hierarchy
public class Main
{
    public static void main(String[] args)
    {
        Manager manager = new Manager("Alice", 80000, "Marketing");
        System.out.println(manager.displayInfo());
 
        Engineer engineer = new Engineer("Bob", 70000, "Software Development");
        System.out.println(engineer.displayInfo());
 
        Secretary secretary = new Secretary("Eve", 50000, "English");
        System.out.println(secretary.displayInfo());
    }
}

In this Java example:

  • Employee is the base class with name, salary, and displayInfo() method.
  • Manager, Engineer, and Secretary are subclasses of Employee.
  • Each subclass inherits the name, salary, and displayInfo() method from Employee and overrides the displayInfo() method to provide specific information about the type of employee.

This example demonstrates hierarchical inheritance in Java:

     Employee
    /   |     \
Manager Engineer Secretary

Each subclass (Manager, Engineer, Secretary) inherits directly from the Employee superclass.

Output:

Manager - Name: Alice, Salary: $80000.0, Department: Marketing
Engineer - Name: Bob, Salary: $70000.0, Specialization: Software Development
Secretary - Name: Eve, Salary: $50000.0, Language: English

Differences Between Inheritance Types in Java

Inheritance in Java comes in different forms, each with its specific characteristics and use cases. The following table summarizes the key differences between single inheritance, multilevel inheritance, and hierarchical inheritance.

Feature / Characteristic Single Inheritance Multilevel Inheritance Hierarchical Inheritance
Definition A subclass inherits from one superclass A subclass inherits from another subclass, forming a chain Multiple subclasses inherit from a single superclass
Structure One-to-one relationship One-to-one-to-one relationship One-to-many relationship
Example class B extends A class C extends B extends A class B extends A
class C extends A
Example Scenario Student inheriting from Person PostgraduateStudent inheriting from GraduateStudent, which inherits from Student Manager, Engineer, and Secretary all inheriting from Employee
Complexity Simple Moderate Moderate to complex
Code Reusability Reuses code from a single class Reuses code from multiple levels of inheritance Reuses code from a single superclass in multiple subclasses
Polymorphism Achieved through method overriding in a single superclass Achieved through method overriding at multiple levels Achieved through method overriding in multiple subclasses
Use Case When a class needs to inherit behavior from one superclass When creating a clear hierarchy with multiple levels When multiple classes share common behavior from a single superclass
Pros Simple to implement and understand Promotes deep hierarchical structures Promotes code reusability across multiple classes
Cons Limited flexibility Can become complex with many levels Can lead to tight coupling and complexity

Advantages of Inheritance in Java

  • Code Reusability: Inheritance allows classes to reuse code from existing classes, reducing redundancy.
  • Method Overriding: Subclasses can provide specific implementations of methods defined in their superclass, promoting flexibility.
  • Polymorphism: Objects of subclasses can be treated as objects of their superclass, enhancing code flexibility and extensibility.
  • Logical Organization: Inheritance helps organize classes in a hierarchical structure, making the code more manageable.
  • Saves Time: It saves time by inheriting fields and methods, reducing the need to write repetitive code.

Disadvantages of Inheritance in Java

  • Tight Coupling: Subclasses are tightly coupled to their superclass, making changes in the superclass affect all subclasses.
  • Unnecessary Inherited Features: Subclasses inherit all methods and attributes, even if they are not needed, potentially adding complexity.
  • Increased Complexity: Inheritance can make the code harder to understand and maintain, especially with deep hierarchies.
  • Refactoring Issues: Refactoring can be difficult and time-consuming if the inheritance hierarchy is complex.
  • Single Inheritance: Java supports single inheritance only, limiting flexibility when a class needs to inherit from multiple sources.
  • Method Overriding Issues: Improper use of method overriding can lead to unexpected behavior and bugs.

FAQs on Inheritance in Java

1. What is inheritance in Java?

Inheritance is a feature of Object-Oriented Programming (OOP) in Java that allows a class (subclass or child class) to inherit properties and behaviors (methods and fields) from another class (superclass or parent class).

2. What are the types of inheritance supported in Java?

Java supports the following types of inheritance:

  • Single inheritance: A subclass inherits from only one superclass.
  • Multilevel inheritance: A subclass can inherit from another subclass.
  • Hierarchical inheritance: Multiple subclasses inherit from the same superclass.
  • Multiple inheritance (through interfaces): A class can implement multiple interfaces, but it can inherit from only one class.

3. When should I use inheritance in Java?

Inheritance should be used when you have a clear hierarchical relationship between classes, and you want to promote code reuse and polymorphism. It’s particularly useful when you have a base class with common behaviors that can be shared among multiple subclasses.

4. Can a class inherit from more than one class in Java?

No, Java does not support multiple inheritance (where a class can inherit from more than one class). However, a class can implement multiple interfaces, which provides a form of multiple inheritance through interface implementation.

5. How can I prevent tight coupling when using inheritance?

To prevent tight coupling, use inheritance only when there is a true “is-a” relationship between the subclass and superclass. Use interfaces when you need to define a contract for multiple classes without creating a strict hierarchical relationship.

6. How does inheritance relate to polymorphism in Java?

Inheritance is closely related to polymorphism in Java. Polymorphism allows objects of subclasses to be treated as objects of their superclass. This is achieved through method overriding, which is enabled by inheritance.

7. When should I use interface inheritance instead of class inheritance?

Use interface inheritance when you want to define a contract (set of methods) that multiple unrelated classes can implement. This allows different classes to share common behaviors without requiring a strict hierarchical relationship.

8. How can I avoid method name conflicts when using inheritance?

If a subclass inherits methods with the same name from multiple superclasses (due to multiple interface implementation), you can explicitly specify which method to call using super.methodName() or by providing an implementation in the subclass that overrides the conflicting methods.

Key Points to Remember

The key points we need to remember about “Inheritance in Java” are:

  • Inheritance in Java allows code reuse by inheriting properties (fields and methods) from a superclass.
  • Subclasses inherit from a superclass using the extends keyword.
  • Subclasses can inherit, add their own functionality, and override inherited methods.
  • Inheritance promotes code reusability, improved organization, and enables polymorphism.
  • Java supports different types of inheritance (single, multilevel, hierarchical) for efficient code structure.
  • Inheritance is key for building modular and scalable Java applications.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.