Skip to main content
Published on

Inheritance in Java

Share:

Introduction

Inheritance is one of the four pillars of object-oriented programming (OOP), alongside encapsulation, polymorphism, and abstraction. Through inheritance, it is possible to create a new class based on an existing one, allowing code reuse and the construction of hierarchical relationships.

Fundamentals of Inheritance

Benefits of Inheritance

  1. Code Reuse: There is no need to rewrite the same code repeatedly. The subclass inherits all members of the superclass.
  2. Extensibility: The existing superclass can be extended to incorporate new attributes and behaviors.
  3. Class Hierarchy: Establishes a hierarchical relationship between superclass and subclass.

Restrictions of Inheritance in Java

In Java, inheritance is implemented using the extends keyword. However, there are some restrictions:

  1. Single Inheritance: Java does not support multiple inheritance through classes. A class can only inherit from a single class.
  2. Constructors and Static Initializers: These are not inherited by subclasses.
  3. Association Relationship: If a class inherits another, it is an "is-a" relationship. For example, if Child is an extension of Parent, then Child is a Parent.

The protected keyword

The protected keyword in Java allows a class member to be accessed directly by any class within the same package or by subclasses. It is a way to provide more access than private, while still restricting generalized access like public.

package com.caffeinealgorithm.programaremjava;

public class Inheritance {
  public void Run() {
    var person = new Child();
    person.information();
    person.favoriteFood();

    /*
      Name: Nelson Silva
      Age: 28
      My favorite food is seafood rice.
    */
  }
}

class Parent {
  protected String lastName = "Silva";

  public void favoriteFood() {
    System.out.println("My favorite food is seafood rice.");
  }
}

class Child extends Parent {
  private String firstName = "Nelson";
  private int age = 28;

  public void information() {
    System.out.printf("Name: %s %s\n", firstName, lastName);
    System.out.printf("Age: %d\n", age);
  }
}

Conclusion

Inheritance is a powerful tool in Java, allowing programmers to write more modular and reusable code. By understanding the fundamentals and nuances of inheritance, you will be better prepared to tackle the complex challenges of object-oriented programming in Java.

Happy coding!