Difference between this and super

Difference between this and super

Difference between this and super

  • 1. Usage:
    • this() is used to invoke a constructor of the same class.
    • super() is used to invoke a constructor of the superclass.
  • 2. Invocation:
    • this() must be the first statement in a constructor and can only invoke another constructor of the same class.
    • super() must also be the first statement in a constructor and can only invoke a constructor of the superclass.
  • 3. Constructor Invocation:
    • this() is used to invoke overloaded constructors within the same class.
    • super() is used to call constructors of the superclass.
  • 4. Implicit Invocation:
    • this() is not implicitly added by the compiler if not explicitly called.
    • super() is implicitly added by the compiler if neither this() nor super() is called explicitly.
  • 5. Inheritance:
    • this() is not affected by inheritance and is resolved at compile time within the same class.
    • super() is used to access constructors of the superclass and is resolved at compile time within the inheritance hierarchy.

6. Example
class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // Invokes superclass constructor
        System.out.println("Child constructor");
    }

    Child(int x) {
        this(); // Invokes overloaded constructor in the same class
        System.out.println("Child constructor with parameter: " + x);
    }
}

In this example:

  • ‘super()’ is used to call the constructor of the superclass ‘Parent’.
  • ‘this()’ is used to call the no-argument constructor of the same class ‘Child’.
  • ‘this()’ can also be used to call an overloaded constructor ‘Child(int x)’ within the ‘Child’ class.

Understanding the difference between ‘this()’ and ‘super()’ is essential for proper constructor chaining and initialization in Java classes and inheritance hierarchies.