Java > Object-Oriented Programming (OOP) > Inheritance > The Super and This Keywords

Illustrating Inheritance, Super, and This Keywords in Java

This example demonstrates inheritance in Java, showcasing how a subclass extends the functionality of a superclass. It highlights the use of the super keyword to access superclass members (constructors and methods) and the this keyword to refer to the current object's members.

Base Class: Animal

The Animal class serves as the base class or superclass. It has a constructor that initializes the name of the animal and a makeSound method providing a default implementation. The getName method is provided to retrieve the animal's name.

public class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
        System.out.println("Animal constructor called with name: " + name);
    }

    public void makeSound() {
        System.out.println("Generic animal sound");
    }

    public String getName() {
        return name;
    }
}

Derived Class: Dog

The Dog class extends the Animal class, inheriting its properties and methods. The constructor of the Dog class calls the Animal class's constructor using super(name). The makeSound method is overridden to provide a more specific sound for dogs. The super.makeSound() call executes the base class's implementation before adding the Dog-specific sound. The this.breed = breed; statement uses this to distinguish the instance variable breed from the constructor parameter breed.

public class Dog extends Animal {
    private String breed;

    public Dog(String name, String breed) {
        super(name); // Call the constructor of the Animal class
        this.breed = breed;
        System.out.println("Dog constructor called with name: " + name + " and breed: " + breed);
    }

    @Override
    public void makeSound() {
        super.makeSound(); // Call the makeSound method of the Animal class
        System.out.println("Woof!");
    }

    public String getBreed() {
        return breed;
    }
}

Main Class: InheritanceExample

The InheritanceExample class demonstrates the usage of the Dog class. An instance of Dog is created, and its methods are called. The output demonstrates how the makeSound method is overridden and how the constructor calls are chained using super.

public class InheritanceExample {
    public static void main(String[] args) {
        Dog myDog = new Dog("Buddy", "Golden Retriever");
        System.out.println("Name: " + myDog.getName());
        System.out.println("Breed: " + myDog.getBreed());
        myDog.makeSound();
    }
}

Concepts Behind the Snippet

Inheritance: Allows a class (subclass) to inherit properties and behaviors from another class (superclass). This promotes code reusability and establishes an IS-A relationship.

Super Keyword: Used to access members (fields and methods) of the superclass. It's particularly useful for calling the superclass's constructor or overridden methods.

This Keyword: Refers to the current object instance. It's used to differentiate between instance variables and local variables with the same name.

Real-Life Use Case

Consider a system for managing different types of employees in a company. You might have a base Employee class with common attributes like name, ID, and salary. Then, you could have subclasses like Manager, Developer, and SalesPerson, each inheriting from the Employee class and adding their specific attributes and behaviors (e.g., Manager might have a list of subordinates, Developer might have a preferred programming language).

Best Practices

  • Use inheritance judiciously. Overuse can lead to complex and brittle class hierarchies.
  • Favor composition over inheritance when possible.
  • Ensure that the subclass maintains the IS-A relationship with the superclass.
  • Use @Override annotation when overriding methods to catch potential errors.

Interview Tip

Be prepared to explain the difference between inheritance and composition. Understand the benefits and drawbacks of each approach and when to use one over the other. Also, know the purpose and usage of the super and this keywords.

When to Use Them

  • Inheritance: Use when you want to create a new class that is a specialized version of an existing class, sharing its properties and behaviors.
  • Super: Use to call the superclass's constructor or access overridden methods from the superclass.
  • This: Use to refer to the current object instance, especially when differentiating between instance variables and local variables with the same name.

Memory Footprint

Inheritance can impact memory footprint as each subclass instance contains the inherited members from the superclass. Deep inheritance hierarchies can lead to increased memory usage. However, this is usually a minor consideration compared to code organization and reusability benefits.

Alternatives

  • Composition: An alternative to inheritance where a class contains instances of other classes as members. This allows for more flexible relationships and avoids the tight coupling of inheritance.
  • Interfaces: Define a contract that classes can implement, allowing for multiple inheritance-like behavior without the complexities of multiple class inheritance.

Pros

  • Code Reusability: Subclasses inherit properties and behaviors from the superclass, reducing code duplication.
  • Extensibility: New classes can be easily created by extending existing classes.
  • Polymorphism: Allows objects of different classes to be treated as objects of a common superclass.

Cons

  • Tight Coupling: Subclasses are tightly coupled to the superclass, making it difficult to modify the superclass without affecting the subclasses.
  • Fragile Base Class Problem: Changes to the superclass can unintentionally break the subclasses.
  • Can lead to complex hierarchies: Deep inheritance hierarchies can be difficult to understand and maintain.

FAQ

  • What is the purpose of the super keyword?

    The super keyword is used to access members (fields and methods) of the superclass from within a subclass. It's commonly used to call the superclass's constructor or access overridden methods.
  • What is the purpose of the this keyword?

    The this keyword refers to the current object instance. It's used to differentiate between instance variables and local variables with the same name or to pass the current object as an argument to another method.
  • What is the difference between inheritance and composition?

    Inheritance is an IS-A relationship where a subclass inherits properties and behaviors from a superclass. Composition is a HAS-A relationship where a class contains instances of other classes as members. Composition offers more flexibility and avoids the tight coupling of inheritance.