What is the Difference Between this and super in Java?

🆚 Go to Comparative Table 🆚

In Java, the super and super() keywords are used in different contexts and serve different purposes:

  • super:
  • A reference variable that refers to parent class objects.
  • Can be used to call parent class variables and methods.
  • Can be used to access specific variables of a superclass.
  • Can be used to invoke any accessible method in the superclass.
  • super():
  • A reference variable that refers to parent class constructors.
  • Can be used to call parent class constructors only.
  • Must be the first statement in the derived class constructor.
  • Used to initialize superclass variables when there is no constructor in the subclass.

In summary, super is used to refer to parent class objects, variables, and methods, while super() is used to call parent class constructors, typically during the construction of a subclass object.

Comparative Table: this vs super in Java

The this and super keywords in Java are used within constructors to call other constructors in the same class or in the superclass. Here is a table summarizing their differences:

Feature this super
Purpose Calls another constructor within the same class Calls a constructor in the superclass of the current class
Representation Represents the current instance of the class Represents the current instance of the parent class
Accessibility Accesses methods and fields of the current class Accesses methods and fields of the parent class
Static Context Can be used from a static context (e.g., System.out.println(this.x)) Cannot be used from a static context (e.g., System.out.println(super.x) will cause a compile-time error)

Some examples of this and super usage include:

  • Using this to call another constructor within the same class:
  class MyClass {
    private int value;

    public MyClass() {
      this(5);
    }

    public MyClass(int value) {
      this.value = value;
    }
  }
  • Using super to call a superclass constructor:
  class SubClass extends SuperClass {
    public SubClass() {
      super();
    }
  }

Remember that this and super cannot be used from a static context, since they represent instance members and methods, not static ones.