difference between this and super keyword in java with example

Difference between this and super keyword in java with example

In Java, both this and super are keywords used to refer to objects, but they are used in different contexts and have different meanings:

this Keyword:
  1. Refers to the Current Object: this refers to the current instance of the class. It represents the object on which the currently executing method was invoked.
  2. Usage: It is often used to differentiate between instance variables and local variables when they have the same name. this is used to access instance variables and methods of the current object.

Example:

this keyword example
/*
 * Author: Zameer Ali
 * */
class MyClass {
    private int num;

    void setNum(int num) {
        // 'this.num' refers to the instance variable, 'num' 
        //refers to the method parameter
        this.num = num; 
    }
}
  1. Constructor Chaining: this is used to call another constructor in the same class.

Example:

Constructor Chaining example using this keyword
/*
 * Author: Zameer Ali
 * */
class MyClass {
    private int num;

    MyClass() {
        // Calls the parameterized constructor with an argument of 0
        this(0); 
    }

    MyClass(int num) {
        this.num = num;
    }
}

super Keyword:
  1. Refers to the Superclass Object: super refers to the superclass object of the current subclass object. It is used to access superclass members (variables and methods) that are hidden by the subclass.
  2. Usage: It is often used to invoke superclass methods, access superclass fields, and call the superclass constructor.

Example:

Super Keyword example
/*
 * Author: Zameer Ali
 * */
class Parent {
    void display() {
        System.out.println("Parent class method");
    }
}

class Child extends Parent {
    void display() {
        super.display(); // Calls the display() method of the parent class
        System.out.println("Child class method");
    }
}
  1. Calling Superclass Constructor: super is used to call the constructor of the superclass from the subclass constructor.

Example:

Calling Superclass Constructor
/*
 * Author: Zameer Ali
 * */
class Parent {
    Parent() {
        System.out.println("Parent class constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // Calls the constructor of the parent class
        System.out.println("Child class constructor");
    }
}

In summary, this refers to the current object and is used to access instance variables, invoke methods, and call constructors within the same class. super refers to the superclass object and is used to access superclass members and call superclass constructors in a subclass.

Leave a Reply

Your email address will not be published. Required fields are marked *