this and super keyword in Java

The keyword super is used to access and call the parent class members (variables and methods).

This keyword this is used to call the current class members (variables and methods). This is required when we have a parameter with the same name as an instance variable (field).

We can use super and this keyword anywhere in a class except a static block and a static method

In the getter we don’t have any parameters so the this keyword is optional

Keyword this

The keyword this is commonly used with constructors and setters.

class People {
    private String name;
    private int age;

    // Create Constructor
    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String move() {
        return this.name + " is moving";
    }

    /**
     * @return String return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return int return the age
     */
    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {

        People myBestFriend = new People("Tim", 35);

        // my best friend Tim changes his name.
        myBestFriend.setName("Jake");

        System.out.println(myBestFriend.getName());
    }
}
Jake

There are this in the People constructor and setName method.

Keyword super

The keyword super is commonly used with method overriding

class ParentClass {
    public void printValue() {
        System.out.println("This is the method in ParentClass");
    }
}

class ChildClass extends ParentClass {
    @Override
    public void printValue() {
        super.printValue();
        System.out.println("The printValue method is called in ChildClass");
    }
}

public class Main {
    public static void main(String[] args) {

        ChildClass childClass = new ChildClass();
        childClass.printValue();

    }
}
This is the method in ParentClass
The printValue method is called in ChildClass

Without the super keyword in the method overriding, in the case it would be recursive call. the method would call it self forever.

Leave a Reply

Your email address will not be published.

ANOTE.DEV