Difference between this() and super() methods?

  • Oct 25, 2020
  • 2
  • 3.6k

Bifference between this() and super() methods?

Answers (2)
Answer Accepted

Difference between this() and super() methods?

this() super()
It represents the current instance of a class. It represents the current instance of a parent class.
It is used to access methods of a current class. It is used to access methods of a parent class.
It also used to call the default constructor of a same class. It is used to call the default constructor of the parent class.

For Java Tutorial,

Java Tutorial

For more Core Java Interview Questions and Answer,

Top 50 Core Java Interview Questions and Answers

In Object-Oriented Programming, both this() and super() are used to call constructors, but they have different purposes and behaviors, and they are used in different contexts.

  1. this():

    • this() is used to call a constructor of the same class from within another constructor of the same class.
    • It's often used when a class has multiple constructors with different parameter lists, and you want to avoid duplicating code by having one constructor delegate some of its initialization tasks to another constructor in the same class.
    • This can be helpful for constructor chaining, where constructors with different parameter sets build upon each other's functionality.
  2. super():

    • super() is used to call a constructor of the superclass (parent class) from within a constructor of a subclass (child class).
    • It's typically used when a subclass constructor needs to perform additional initialization that is specific to the subclass, but it also needs to ensure that the initialization of the superclass is executed.
    • When you create an instance of a subclass, the constructors of both the subclass and its superclass are called in the process, and super() can be used to control the flow of this initialization.

Here's a simple example in Java to illustrate the differences:

class Animal {
    String type;

    Animal(String type) {
        this.type = type;
    }
}

class Dog extends Animal {
    String breed;

    Dog(String type, String breed) {
        super(type); // Calls the constructor of the superclass (Animal)
        this.breed = breed;
    }
}

In this example, the Dog class extends the Animal class. The Dog constructor calls super(type) to invoke the constructor of the Animal class to properly initialize the type field inherited from the superclass. Then, it initializes its own breed field.

In summary, this() is used to call constructors within the same class, while super() is used to call constructors of the superclass in a subclass. Both this() and super() are useful for managing constructor logic and ensuring proper initialization in inheritance hierarchies.

Submit your answer