-5

In my given Image you can see that I have created a Class named employee with one variable with no assigned value.Also I have given getter and setter methods. Now the queston i have is that , in the Setter method i.e (setsalary) , I am taking a integer value into the variable s and then assigning it to the salary variable. Now when I create an object of that particular class ( as you can see in the image), how does the program knows that the given value of salary has to be assigned to the salary of the object i.e (John.salary) , I mean i have only written salary=s; and nothing else. How does the program setts the value exactly to the object ?

enter image description here

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • _..I mean i have only written salary=s.._ False, you have declared `salary` as a class property and then assigned a value to it. I recommend to read over basics of OOP – B001ᛦ Jun 05 '20 at 16:49
  • Does this answer your question? [What is the difference between a local variable, an instance field, an input parameter, and a class field?](https://stackoverflow.com/questions/20671008/what-is-the-difference-between-a-local-variable-an-instance-field-an-input-par) – Joe Jun 20 '20 at 14:02

1 Answers1

1

how does the program knows that the given value of salary has to be assigned to the salary of the object i.e (John.salary) , I mean i have only written salary=s; and nothing else

The missing ingredient is the this keyword:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

What isn't written there is that the this keyword is OPTIONAL, thus this line:

salary=s;

and this line are equivalent:

this.salary=s;

So it knows which instance (John in this case) to use because there is actually an invisible "this" in front of "salary" telling it to assign to the CURRENT OBJECT.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40