Java Interview Prep: Mastering this and super Keywords


Understanding this and super in Java

The this and super keywords are critical in object-oriented programming for managing references to the current class instance and its superclass. Here’s a breakdown of their usage, followed by potential interview questions to help in preparation.


this Keyword

The this keyword refers to the current instance of the class.

Common Uses of this:

  1. Referencing Instance Variables:

    • Resolves ambiguity when instance variables are shadowed by method or constructor parameters.
    class Person {
        String name;
    
        Person(String name) {
            this.name = name; // Resolves shadowing
        }
    }
  2. Calling Another Constructor in the Same Class:

    • Allows constructor chaining within the same class.
    class Person {
        String name;
        int age;
    
        Person(String name) {
            this(name, 0); // Calls another constructor
        }
    
        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
  3. Passing the Current Instance as an Argument:

    class Example {
        void print(Example e) {
            System.out.println("Method called with: " + e);
        }
    
        void callMethod() {
            this.print(this); // Pass the current instance
        }
    }
  4. Returning the Current Instance:

    • Used in method chaining.
    class Builder {
        Builder setName(String name) {
            System.out.println("Name set: " + name);
            return this;
        }
    }

super Keyword

The super keyword refers to the parent class of the current object.

Common Uses of super:

  1. Accessing Parent Class Methods or Variables:

    • Resolves ambiguity when the child class overrides parent methods or hides variables.
    class Parent {
        String name = "Parent";
        void show() {
            System.out.println("Parent method");
        }
    }
    
    class Child extends Parent {
        String name = "Child";
        void show() {
            super.show(); // Calls Parent method
            System.out.println(super.name); // Refers to Parent's name
        }
    }
  2. Calling Parent Class Constructor:

    • Used to explicitly call a parent class constructor.
    class Animal {
        Animal(String type) {
            System.out.println("Animal type: " + type);
        }
    }
    
    class Dog extends Animal {
        Dog(String breed) {
            super("Mammal"); // Calls Animal's constructor
            System.out.println("Dog breed: " + breed);
        }
    }
  3. Invoking Parent Class Constructor in Constructor Overloading:

    class Parent {
        Parent(String name) {
            System.out.println("Parent: " + name);
        }
    }
    
    class Child extends Parent {
        Child() {
            super("Default Parent"); // Invokes Parent's constructor
        }
    }

Key Differences Between this and super




Interview Questions on this and super

Beginner Questions:

  1. What is the difference between this and super in Java?
  2. Can you use this in a static method? Why or why not?
  3. Can super be used to call a constructor? Provide an example.
  4. What happens if you do not explicitly use super() in a subclass constructor?

Intermediate Questions:

  1. Explain the purpose of this() and super() in constructor chaining.
  2. Can you use this() and super() in the same constructor? Why or why not?
  3. Write a program to demonstrate method overriding where the super keyword is used to call a hidden parent method.
  4. How does Java handle this and super in multilevel inheritance?

Advanced Questions:

  1. Explain a scenario where using super could avoid ambiguity in a program.
  2. In what situation would you prefer to use this over super?
  3. Can this and super be used together in the same method or constructor? If yes, demonstrate with an example.
  4. What is the purpose of this in fluent APIs or method chaining?

Sample Program for Practice

Demonstrating this and super:

class Vehicle {
    String type = "Vehicle";

    void display() {
        System.out.println("This is a vehicle");
    }
}

class Car extends Vehicle {
    String type = "Car";

    void display() {
        System.out.println("This is a car");
    }

    void printInfo() {
        System.out.println(this.type);  // Refers to Car's type
        System.out.println(super.type); // Refers to Vehicle's type
        this.display();                // Calls Car's display method
        super.display();               // Calls Vehicle's display method
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.printInfo();
    }
}

Expected Output:

Car Vehicle This is a car This is a vehicle

Practice Questions:

  1. Write a Java program that uses super to call a parent class's parameterized constructor.
  2. Modify a program to demonstrate how this and super can be used together in a multilevel inheritance hierarchy.
  3. Explain what happens if you omit super() in a subclass constructor.

By practicing these questions and concepts, you will develop a solid understanding of how to use this and super effectively in Java.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete