What is the difference between this() and super()?

this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

In Java, this() and super() are both used to invoke constructors, but they are used in different contexts and have different purposes:

  1. this():
    • It is used to invoke the current class constructor.
    • It is often used to invoke one constructor from another within the same class.
    • It cannot be used to invoke a constructor from a superclass.

    Example:

    java
    public class MyClass {
    private int value;
    // Parameterized constructor
    public MyClass(int value) {
    this.value = value;
    }

    // Default constructor that invokes the parameterized constructor using this()
    public MyClass() {
    this(10); // invoking the parameterized constructor
    }
    }

  2. super():
    • It is used to invoke the constructor of the immediate superclass (the parent class).
    • It is often used when a subclass wants to call a constructor of its superclass.
    • If used, it must be the first statement in the subclass constructor.

    Example:

    java
    public class SubClass extends SuperClass {
    private int subValue;
    // Parameterized constructor in the subclass
    public SubClass(int subValue) {
    super(); // invoking the constructor of the superclass
    this.subValue = subValue;
    }
    }

In summary:

  • this() is used to invoke a constructor within the same class.
  • super() is used to invoke a constructor from the immediate superclass.
  • Both this() and super() must be the first statement in a constructor if they are used.