Using `this` and `super` Keywords Together in Java

Respondido utilizando GPT-4o-mini por Java Q&A Hub

Pregunta:

Can "this" and "super" keywords be used together In Java?

Respuesta:

Yes, in Java, the this and super keywords can be used together, but they serve different purposes and are used in different contexts.

  1. this Keyword: The this keyword refers to the current instance of the class. It is often used to differentiate between instance variables and parameters with the same name, or to call other constructors in the same class.

  2. super Keyword: The super keyword refers to the superclass (parent class) of the current object. It is used to access superclass methods and constructors.

Using this and super Together

You can use both this and super in the same context, but they cannot be used interchangeably. For example, you might use this to refer to an instance variable and super to call a method from the superclass.

Here’s an example to illustrate their usage together:

class Parent {
    int value;

    Parent(int value) {
        this.value = value; // 'this' refers to the current instance of Parent
    }

    void display() {
        System.out.println("Value in Parent: " + value);
    }
}

class Child extends Parent {
    int value;

    Child(int value) {
        super(value); // 'super' calls the constructor of Parent
        this.value = value; // 'this' refers to the current instance of Child
    }

    void display() {
        super.display(); // Calls the display method of Parent
        System.out.println("Value in Child: " + this.value); // 'this' refers to Child's value
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child(10);
        child.display();
    }
}

Output:

Value in Parent: 10
Value in Child: 10

In this example:

  • The super(value) call in the Child constructor invokes the Parent constructor, passing the value parameter.
  • The this.value in the Child constructor assigns the value to the Child instance variable.
  • The super.display() method call in the Child class invokes the display method from the Parent class.

So, while this and super can be used in the same class, they refer to different contexts and are used for different purposes.