Page Content

Tutorials

What is Inheritance in Java? & What is Inheritance OOP?

Inheritance in Java

In Java, inheritance is a key idea in object-oriented programming (OOP) that enables a class to inherit the characteristics and actions of another class. Embodying a “is-a” relationship, it facilitates hierarchical information management and encourages code reuse.

Concept of Inheritance

The new class can be derived from an existing class when it requires some of the code from that class. The existing class is referred to as the superclass in this context (also called the parent or base class), and the derived class is referred to as the subclass (also called the child or derived class). Every variable and method defined by the superclass is inherited by a subclass, which is a more specialised version of its superclass with additional particular features.

Use of inheritance

To create this inheritance relationship, utilise the extends keyword. Multiple inheritance for classes is not supported by Java since a class can only directly extend one superclass.

The primary uses of inheritance include:

  • Code Reusability: It enables developers to leverage existing code without rewriting it, which speeds up development and reduces redundancy.
  • Hierarchical Classification: Inheritance facilitates hierarchical classification, making complex systems more manageable by organizing objects in a logical, top-down structure. A superclass defines common traits, which are then inherited and specialized by subclasses.
  • Polymorphism Support: This mechanism also supports polymorphism by allowing a general interface for a class of actions, with specific implementations determined at runtime through method overriding.
  • Extensibility: Inheritance allows for additional functionality in subclasses without requiring changes to the base class.
  • Reduced Object Memory: Some sources also state that inheritance is used to reduce object memory.

By creating a hierarchy where subclasses extend superclasses, Java programs can be designed more efficiently and robustly.

Consider this simple example illustrating the extends keyword, superclass, and subclass:

// Create a superclass.
class Animal {
    String species;
    void eat() {
        System.out.println(species + " is eating.");
    }
}
// Create a subclass by extending class Animal.
class Dog extends Animal {
    String name;
    void bark() {
        System.out.println(name + " is barking.");
    }
}
class SimpleInheritance {
    public static void main(String args[]) {
        Animal myAnimal = new Animal();
        myAnimal.species = "Mammal";
        System.out.println("Contents of myAnimal:");
        myAnimal.eat(); // Mammal is eating.
        Dog myDog = new Dog();
        myDog.species = "Canine"; // Inherited from Animal
        myDog.name = "Buddy";
        System.out.println("\nContents of myDog:");
        myDog.eat();  // Canine is eating.
        myDog.bark(); // Buddy is barking.
    }
}

Output:

Contents of myAnimal:
Mammal is eating.
Contents of myDog:
Canine is eating.
Buddy is barking.

In this example, Dog extends Animal, so Dog objects inherit the species variable and eat() method from Animal.

The super Keyword

In Java, the current class’s immediate superclass is referred to using the super keyword. Two primary forms exist for it:

  1. Calling a superclass constructor: When a subclass object is created, the constructors in the class hierarchy are executed in order of derivation, from superclass to subclass. To explicitly call a superclass constructor from a subclass constructor, you use super(arg-list). This call must be the very first statement executed inside the subclass constructor. If you don’t explicitly call super(), the compiler automatically inserts a call to the superclass’s no-argument constructor.
  2. Accessing superclass members: The super keyword can also be used to access a member (either a method or an instance variable) of the superclass that has been hidden by a member with the same name in the subclass. This helps differentiate between the superclass’s member and the subclass’s member when they share the same name.

Preventing Inheritance: Classes and Methods

For security or design reasons, inheritance or method overriding may occasionally need to be avoided. This is the use of the final keyword.

  • final Methods: Declaring a method as final prevents any subclass from overriding it. If a subclass attempts to override a final method, it will result in a compile-time error. This can sometimes offer a performance enhancement, as the compiler can inline calls to final methods.
  • If the commented-out importantMethod() in SubClassAttemptingOverride were uncommented, the program would fail to compile.
  • final Classes: Declaring a class as final prevents it from being inherited by any other class. This implicitly makes all of its methods final as well. It is illegal to declare a class as both abstract and final, because an abstract class relies on subclasses for complete implementation, which a final class cannot provide.
  • If AttemptToExtendFinal were uncommented, the program would fail to compile because FinalClass is final.

Java programmers are able to create software systems that are reliable, reusable, and maintainable by comprehending and effectively applying these fundamental inheritance notions.

Types of Inheritance in Java

A key tenet of object-oriented programming in Java is inheritance, which permits one class to inherit the traits and capabilities of another class, encouraging code reuse and establishing a hierarchical object classification. The class that inherits is called the superclass (sometimes called the parent or base class), and the class that inherits is called the subclass (also called the child or derived class). This type of relationship is frequently called a “is-a” relationship.

Types of Inheritance in Java
Types of Inheritance in Java

In the context of Java, several kinds of inheritance structures are examined, however the fundamental idea of inheritance stays the same:

  1. Single Inheritance: One inheritance is the simplest type, in which a subclass extends just one superclass. Java’s extends keyword allows classes to have a single inheritance.
  2. Multilevel Inheritance: A multi-layered hierarchy is created using multilevel inheritance, which is a chain in which a class inherits from a superclass, and then another class inherits from that child class. Class B, for example, extends Class A, and Class C extends Class B.
  3. Hierarchical Inheritance: One superclass is inherited by several subclasses in a hierarchical inheritance hierarchy.
  4. Multiple Inheritance: A situation known as “multiple inheritance” occurs when a class tries to inherit directly from two or more superclasses at the same time. Java doesn’t support multiple inheritance for classes directly. This limitation mainly stems from possible “priority problems” or “ambiguity issues” that may occur when methods in different parent classes have the same name, making it difficult to decide which method implementation to employ.
  5. Hybrid Inheritance: Hybrid inheritance is a kind of inheritance that combines multiple and single inheritance. Pure hybrid inheritance is likewise not directly possible for classes in Java since multiple inheritance of classes is not allowed.

However, Java provides a different way to use interfaces to get some of the advantages of multiple inheritance. A class can implement multiple interfaces, allowing it to incorporate diverse functionalities or characteristics. Although they can now include default methods since Java 8, interfaces are often not used to store state (instance variables). Because the concrete method definitions are provided by the implementing class or because special rules are in place to address conflicts between default methods, this technique avoids the ambiguity problems associated with multiple class inheritance. Interfaces have the ability to create their own inheritance hierarchies by extending other interfaces.

Index