JAVA - Zero to Hero / Object Oriented Programming (OOP)

‘this’ and ‘super’ Keywords

1️⃣ this Keyword

The this keyword is a reference to the current object.

It's used when local variable names are the same as instance variables, or to call other methods/constructors in the same class.

🧠 Why Use this?

  • To avoid naming conflicts between local and instance variables

  • To call one constructor from another

  • To pass the current object as an argument

🔸 Example:

class Student {
    String name;

    Student(String name) {
        this.name = name; // ‘this’ refers to the instance variable
    }

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

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Riya");
        s.display();
    }
}
Student Name: Riya

this() — Call Constructor from Constructor

class Example {
    Example() {
        System.out.println("Default Constructor");
    }

    Example(String msg) {
        this();  // calls the default constructor
        System.out.println(msg);
    }
}

public class Main {
    public static void main(String[] args) {
        new Example("Message Constructor");
    }
}
Default Constructor
Message Constructor

2️⃣ super Keyword

The super keyword is a reference to the parent (super) class.

It is used to:

  • Call parent class constructors

  • Access parent class methods or variables overridden or hidden in the child class

🔸 Example: Calling Parent Method

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

class Dog extends Animal {
    void sound() {
        super.sound();  // calls parent version
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.sound();
    }
}
Animal makes sound
Dog barks

🔸 Example: Calling Parent Constructor

class Animal {
    Animal() {
        System.out.println("Animal constructor");
    }
}

class Dog extends Animal {
    Dog() {
        super();  // calls parent constructor
        System.out.println("Dog constructor");
    }
}

public class Main {
    public static void main(String[] args) {
        new Dog();
    }
}
Animal constructor
Dog constructor