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:
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
// Parameterized constructorpublic class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
// Default constructor that invokes the parameterized constructor using this()
public MyClass() {
this(10); // invoking the parameterized constructor
}
}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
// Parameterized constructor in the subclasspublic class SubClass extends SuperClass {
private int subValue;
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()
andsuper()
must be the first statement in a constructor if they are used.