DEV Community

Surya
Surya

Posted on

this and super Keyword


What is this in Java?
Enter fullscreen mode Exit fullscreen mode

The this keyword in Java refers to the current object of the class. It helps differentiate between instance variables and parameters or call methods/constructors within the same class.

When do we use this?
Enter fullscreen mode Exit fullscreen mode

When local variables and instance variables have the same name.

To call another constructor in the same class.

How is this used?
Enter fullscreen mode Exit fullscreen mode
  1. To refer to the current object variable.

  2. To pass the current object as a parameter.

  3. To call another constructor in the same class.

Why We use?
Enter fullscreen mode Exit fullscreen mode

To remove confusion between local and instance variable

Program:

class Student {
    int Rollno;
    String Name;
    int Age;

    Student(int Rollno, String Name, int Age) {
        this.Rollno = Rollno;
        this.Name = Name;
        this.Age = Age;
    }

    void display() {
        System.out.println(Rollno + " " + Name + " " + Age);
    }
}

public class TestStudent {
    public static void main(String[] args) {
        Student s1 = new Student(101, "Arun",24);

        s1.display();
    }
}

Output:
101 Arun 24


Enter fullscreen mode Exit fullscreen mode
What is super in Java?
Enter fullscreen mode Exit fullscreen mode

The super keyword in Java is used to refer to the immediate parent class object. It comes in handy when working with inheritance.

When do we use super?
Enter fullscreen mode Exit fullscreen mode

When you want to call the parent class constructor.

When a child class overrides a method but you still need the parent class version.

To access parent class variables when they are hidden by child class variables.

How is super used?
Enter fullscreen mode Exit fullscreen mode
  1. To call the parent class constructor.

  2. To access parent class variables.

  3. To access parent class methods.

Why We use?
Enter fullscreen mode Exit fullscreen mode

We use the super keyword in java to access parent class variable and methods

Program:

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

class Dog extends Animal {
    void show() {
        super.show();
        System.out.println("dog is barking");
    }
}

public class TestName {
    public static void main(String args[]) {
        Dog d1 = new Dog();
        d1.show();
    }
}

Output:

Animal sound
dog is barking

Enter fullscreen mode Exit fullscreen mode

Top comments (0)