Sobes.tech
Junior — Middle

Explain the difference between the keywords this and super in Java and in which situations they are used.

sobes.tech AI

Answer from AI

In Java, the keyword this refers to the current object, that is, the instance of the class in which the method is executed. It is used to access the fields and methods of the current object, especially when parameter names and field names coincide:

class Example {
    int value;
    Example(int value) {
        this.value = value; // this.value — field, value — parameter
    }
}

The keyword super is used to refer to methods and constructors of the parent (superclass) class. This is useful when you need to call an overridden method of the superclass or invoke its constructor:

class Parent {
    void show() {
        System.out.println("Parent");
    }
}

class Child extends Parent {
    void show() {
        super.show(); // call to parent method
        System.out.println("Child");
    }
}

In summary:

  • this — the current object
  • super — the object of the parent class (to call its methods or constructor)

They are used to manage access to class members and inheritance.

Explain the difference between the keywords this and… - sobes.tech