Explain how you can use ‘this’ keyword inside a constructor

date:2024-06-05 12:29:20 author:admin browse: time View comments Add Collection

Explain how you can use ‘this’ keyword inside a constructor

Explain how you can use ‘this’ keyword inside a constructor.

The ‘this’ keyword in a constructor refers to the current instance of the class. It’s used to distinguish between class attributes and parameters when they have same names. For example, if we have a class ‘Person’ with attribute ‘name’, and our constructor also has a parameter named ‘name’, we can use ‘this.name’ to refer to the class attribute, and ‘name’ to refer to the parameter.

Here is an example:

public class Person {
    String name;
    public Person(String name) {
        this.name = name;
    }
}
In this code, ‘this.name’ is the class attribute, and ‘name’ is the constructor parameter. The line ‘this.name = name;’ assigns the value of the constructor parameter to the class attribute. Without ‘this’, there would be ambiguity as both the class attribute and constructor parameter are named ‘same’.