educative.io

Understanding Encapsulation Using Examples - Learn Object-Oriented

Why in the good example in if condition we need to provide
this.username == this.username
we could have only use username == username


Course: Learn Object-Oriented Programming in Java - Learn Interactively
Lesson: Understanding Encapsulation Using Examples - Learn Object-Oriented Programming in Java

Hello @Estiak
Thanks for reaching out to us.
The main motto of using this keyword is to differentiate the formal parameter and data members of the class. If in case, the formal parameter and data members of the class are the same, then it leads to ambiguity. So, in order to differentiate between the formal parameter and the data member of the class, the data member of the class must be preceded by the “this” keyword.
In our code example, userName is the class variable and declare in function too that’s why we used this keyword with a userName that represents the current instance of a class. It is used to differentiate variables of the class (this. username) and formal parameters of the method/function(username).
Hope it will help, Happy Learning :slight_smile:

if i would have used different parameters in the constructor like in the place of userName i used name and declared it userName = name
than should i needed to use the this operator in if condition


Course: Learn Object-Oriented Programming in Java - Learn Interactively
Lesson: Understanding Encapsulation Using Examples - Learn Object-Oriented Programming in Java

Yes, then you can use it without the this keyword.
Thank you

thank you for your instant reply and assist


Course: Learn Object-Oriented Programming in Java - Learn Interactively
Lesson: Solution Review: Implement the Complete Student Class - Learn Object-Oriented Programming in Java

1 Like