In Java, super() and this() are special constructor calls used for constructor chaining. The super() keyword invokes the parent class constructor, while this() invokes another constructor of the same class.
super() in Java
super() is used in a subclass constructor to call the constructor of its parent class, ensuring the parent part of the object is initialized first. Calls the parent class constructor.
- Must be the first statement in the subclass constructor.
- Can pass parameters to call a specific parent constructor.
- Helps in constructor chaining across classes in inheritance.
- If not used explicitly, Java inserts a default super() automatically (if parent has no-arg constructor).
Syntax
super();
super(arguments);
Example: This code demonstrates the use of super() to call the parent class constructor from a child class constructor in Java.
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
Child() {
super();
System.out.println("Child constructor");
}
public static void main(String[] args) {
new Child();
}
}
Output
Parent constructor Child constructor
Explanation:
- new Child() calls the Child constructor.
- super() invokes the Parent constructor first.
- After the parent constructor executes, control returns to the child constructor.
this() in Java
this() is used in a class constructor to call another constructor of the same class, allowing constructor chaining and reducing code duplication.
- Calls another constructor in the same class.
- Must be the first statement in the constructor.
- Can pass parameters to call a specific constructor.
- Helps in reusing code within the same class.
- Only used for constructor chaining, not for calling parent constructors.
Syntax
this();
this(arguments);
Example: This code demonstrates the use of this() to call another constructor of the same class in Java.
class Demo {
Demo() {
this(10);
System.out.println("No-arg constructor");
}
Demo(int a) {
System.out.println("Parameterized constructor");
}
public static void main(String[] args) {
new Demo();
}
}
Output
Parameterized constructor No-arg constructor
Explanation:
- new Demo() calls the no-argument constructor.
- this(10) invokes the parameterized constructor first.
- After the parameterized constructor executes, control returns to the no-argument constructor.
Difference Between super() and this()
Feature | super() | this() |
|---|---|---|
Purpose | Calls the parent class constructor | Calls another constructor in the same class |
Scope | Refers to superclass | Refers to current class |
Usage | Used in subclass constructor | Used in any constructor of the same class |
Position | Must be the first statement in constructor | Must be the first statement in constructor |
Parameters | Can pass arguments to parent constructor | Can pass arguments to another constructor in the same class |
Constructor Chaining | Chains to parent class constructor | Chains to another constructor in the same class |