Skip to main content
Published on

More About Inheritance in Java

Share:

Introduction

While the first introduction to inheritance in Java helps us understand its fundamental concepts, in this article we will dive deeper into more advanced topics such as method overriding and abstraction.

Method Overriding

When a subclass inherits from a superclass, it also inherits its methods. However, in many cases we want the subclass to have a different implementation for one or more of those methods. This is achieved through method overriding, using the @Override annotation.

Advantages of Method Overriding:

  1. Flexibility: Allows a subclass to provide a specific implementation of a method that is already provided by its superclass.
  2. Code Reuse: Even when inheriting a method from a superclass, we can adjust it to the specific needs of the subclass.
  3. Improved Readability: By using the @Override annotation, we clearly signal that the method is being overridden, making the code easier to understand.
package com.caffeinealgorithm.programaremjava;

public class MoreAboutInheritance {
  public void Run() {
    var person = new Son();
    person.info();
    person.favoriteFood();

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

class Father {
  protected String lastName = "Silva";

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

class Son extends Father {
  private String firstName = "Nelson";
  private int age = 28;

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

  @Override
  public void favoriteFood() {
    System.out.println("My favorite food is lasagna.");
  }
}

Abstraction and Abstract Methods

The term "abstract" was briefly mentioned earlier. This is an important concept in Java, allowing you to create classes and methods that cannot be instantiated. They are, essentially, blueprints that other classes must follow.

  1. Abstract Classes: Cannot be instantiated directly. They serve as a base for other classes.
  2. Abstract Methods: Are declared in the abstract class but have no body. Subclasses must provide the implementation of these methods.

We will explore this topic in detail in an upcoming article, ensuring a complete understanding of abstraction and how it integrates with inheritance.

Conclusion

Inheritance, combined with concepts such as method overriding and abstraction, makes object-oriented programming a powerful tool for creating modular and reusable software. These are just some of the advanced concepts in Java, and continuing to explore them will deepen your knowledge even further.

Happy coding!