Difference between this and super Keyword in Java

1. Introduction

In Java, this and super are two keywords that have special significance in the context of classes and inheritance. The this keyword is a reference to the current object — the object whose method or constructor is being called. The super keyword is used to access methods and constructors of an object's superclass.

2. Key Points

1. this is used to refer to the current class's members (variables, methods, constructors).

2. super is used to refer to the parent class's members.

3. this is commonly used for disambiguation, constructor chaining, and passing the current instance.

4. super is commonly used to override the behavior of a superclass.

3. Differences

this super
References the current object. References the immediate parent object.
Can be used to call constructors, methods, and to access fields of the current class. Can be used to call methods, constructors, and to access fields of the superclass.
Cannot be used in a static context. Cannot be used in a static context.

4. Example

class ParentClass {
    String name;

    ParentClass(String name) {
        this.name = name;
    }

    void display() {
        System.out.println("Name from ParentClass: " + name);
    }
}

class ChildClass extends ParentClass {
    String name;

    ChildClass(String name, String parentName) {
        super(parentName); // Calls the constructor of the ParentClass
        this.name = name;
    }

    void display() {
        super.display(); // Calls the display method of ParentClass
        System.out.println("Name from ChildClass: " + this.name);
    }
}

public class Main {
    public static void main(String[] args) {
        ChildClass child = new ChildClass("ChildName", "ParentName");
        child.display();
    }
}

Output:

Name from ParentClass: ParentName
Name from ChildClass: ChildName

Explanation:

1. ParentClass has a constructor that initializes the name field using this.name to refer to the current instance's name field.

2. ChildClass extends ParentClass and also has a name field. It uses this.name to refer to its own name field and super(name) to call the superclass's constructor.

3. The display method in ChildClass uses super.display() to invoke the superclass's display method and this.name to refer to its own name field.

5. When to use?

- Use this when you need to refer to the current class’s members or to invoke another constructor of the same class.

- Use super when you need to access members of the superclass or to call the superclass's constructor from a subclass.

Comments