Java Inheritance

Introduction

Hello there, fellow coder! Ever wondered how you can reuse code in Java and make your programs more efficient? Well, that’s where Java inheritance comes into play. In this tutorial, we’ll dive deep into the concept of inheritance in Java, a fundamental aspect of object-oriented programming. So, buckle up and let’s get started!

Understanding the Basics of Java Inheritance

Inheritance, in the world of Java, is a mechanism where one class acquires, or “inherits,” the properties (fields) and behaviors (methods) of another class. The class which is inherited is called the “superclass” or “parent class,” and the class that does the inheriting is called the “subclass” or “child class.” In Java, we use the keyword extends to denote inheritance.

The Concept of Superclass and Subclass

Imagine a general class called Animal. This class has properties like age and weight, and methods like eat and sleep. Now, let’s say we have a specific animal, like a Dog. A Dog is an Animal, right? It has an age, a weight, and it can certainly eat and sleep. But a Dog can also bark, something that not all animals can do. In this scenario, Animal is the superclass, and Dog is the subclass that extends the Animal class and adds an extra bark method.

The above imaginary situation is coded in the following code:

class Animal {
  int age;
  double weight;

  void eat() {
    System.out.println("Eating...");
  }

  void sleep() {
    System.out.println("Sleeping...");
  }
}

class Dog extends Animal {
  void bark() {
    System.out.println("Barking...");
  }
}
Java

Here’s a diagram illustrating the concept of Java inheritance in the context of the Animal and Dog classes. The Dog class, as a subclass, inherits properties and methods from the Animal superclass and also adds its own method bark().

Concept of Java inheritance
Illustrated Concept of Java inheritance

The extends Keyword in Java

In Java, we use the extends keyword to create a subclass. The extends keyword signals that you’re making a new class that derives from an existing one. The existing class is the superclass, and the new class is the subclass. In the Dog example above, we used extends to make Dog a subclass of Animal.

Java Inheritance in Action

Let’s see Java inheritance in action with a complete example. We’ll create a Vehicle superclass and a Car subclass that extends Vehicle. The Vehicle class has a brand attribute and a honk method, while the Car class adds a modelName attribute.

class Vehicle {
  protected String brand = "Ford"; // Vehicle attribute

  public void honk() { // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang"; // Car attribute

  public static void main(String[] args) {
    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}
Java

When you run this code, it outputs:

Tuut, tuut!
Ford Mustang

Java Inheritance Examples

Let’s dive into some more code examples to solidify our understanding of Java inheritance.

Code Example 1: Creating a Superclass and a Subclass

In this example, we’ll create a Person superclass with name and age attributes, and a sayHello method. We’ll then create a Student subclass that extends Person and adds a grade attribute.

class Person {
  protected String name;
  protected int age;

  public void sayHello() {
    System.out.println("Hello, my name is " + name + " and I'm " + age + " years old.");
  }
}

class Student extends Person {
  int grade;

  public void sayHello() {
    super.sayHello();
    System.out.println("I'm in grade " + grade + ".");
  }
}
Java

Code Example 2: Overriding Methods in a Subclass

In this example, we’ll override the sayHello method in the Student subclass. Overriding is a feature in Java that allows a subclass to provide a specific implementation of a method that is already provided by its superclass.

class Student extends Person {
  int grade;

  @Override
  public void sayHello() {
    System.out.println("Hey there! I'm " + name + ", I'm " + age + " years old, and I'm in grade " + grade + ".");
  }
}
Java

The super Keyword in Java Inheritance

In Java, super is a reference variable that is used to refer to the immediate parent class object. Whenever you create an instance of a subclass, an instance of the parent class is created implicitly, which is referred to by the super keyword.

The final Keyword in Java Inheritance

The final keyword in Java is used to restrict the user. The final keyword can be used in many contexts. One of these is to prevent inheritance. If you make a class final, it cannot be subclassed.

Wrapping Up

And that’s a wrap on Java inheritance! We’ve covered the basics, dived into some code examples, and explored the super and final keywords. Understanding inheritance is crucial for Java programming as it promotes code reusability and a clean, organized structure. So keep practicing and happy coding!

Frequently Asked Questions (FAQ)

  • What is inheritance in Java?

    Inheritance in Java is a mechanism where one class acquires the properties (fields) and behaviors (methods) of another class. It’s a fundamental aspect of object-oriented programming that promotes code reusability and a clean, organized structure.

  • How does the extends keyword work in Java?

    In Java, we use the extends keyword to create a subclass from a superclass. The extends keyword signals that you’re making a new class that derives from an existing one. The existing class is the superclass, and the new class is the subclass.

  • What is a superclass and a subclass in Java?

    In the context of Java inheritance, the superclass is the class that is being inherited from, and the subclass is the class that is doing the inheriting. The subclass acquires the properties and behaviors of the superclass.

  • How can I override a method in a subclass?

    In Java, you can override a method in a subclass by declaring a method in the subclass using the exact same method name, return type, and parameters as in its superclass. The @Override annotation is used above the method to signify that the method is intended to override a method in the superclass.

  • What is the super keyword in Java?

    In Java, super is a reference variable that is used to refer to the immediate parent class object. It’s often used in subclass methods to call a method or access a property of the superclass.

  • How does the final keyword restrict inheritance?

    The final keyword in Java is used to restrict the user. If you make a class final, it cannot be subclassed. This means no other class can inherit from a final class.

  • Can a subclass inherit from multiple superclasses?

    No, a subclass in Java cannot inherit from multiple superclasses. Java does not support multiple inheritance due to the “Diamond Problem.” However, a class can implement multiple interfaces, which is a way to achieve a form of multiple inheritance.

  • What is the difference between public, private, and protected in Java inheritance?

    These are access modifiers in Java. public members are accessible everywhere, private members are only accessible within the same class, and protected members are accessible within the same package and also available to any subclasses, even if they’re in a different package.

  • How does constructor chaining work in Java inheritance?

    Constructor chaining is a process where a constructor calls another constructor in the same or superclass. This process helps to ensure that the initialization of a class and its superclass is completed correctly. In Java, constructor chaining is done using the super keyword.

  • Can we inherit constructors in Java?

    No, constructors are not inherited in Java. However, a subclass constructor can call a superclass constructor using the super keyword. This is often done to ensure that the superclass is properly initialized before the subclass is initialized.

  • Understanding Java Polymorphism
  • Java Abstraction Explained
  • A Deep Dive into Java Interfaces
  • Mastering Java Classes and Objects
  • Exploring Java Encapsulation

Remember, practice makes perfect. Keep coding and exploring new concepts. Happy learning!

Scroll to Top