When we create a setter method in java , how does java know to which variable we want to set the given value from the setter ? read discription please

huangapple go评论64阅读模式
英文:

When we create a setter method in java , how does java know to which variable we want to set the given value from the setter ? read discription please

问题

在我提供的图片中,您可以看到我创建了一个名为"employee"的类,其中包含一个未赋值的变量。我还提供了getter和setter方法。现在我有一个问题,就是在setter方法(即"setsalary")中,我将一个整数值存储在变量"s"中,然后将其赋值给"salary"变量。现在,当我创建该特定类的一个对象(如您在图片中看到的),程序如何知道将给定的工资值赋值给对象的工资,即(John.salary)?我的意思是,我只写了"salary=s;",没有其他操作。程序如何确切地将值设置到对象中?

(图片已略去)

英文:

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 ?

When we create a setter method in java , how does java know to which variable we want to set the given value from the setter ? read discription please

答案1

得分: 1

缺失的关键是this 关键字:

在实例方法或构造函数内部,this 是对当前对象的引用 — 即调用该方法或构造函数的对象。您可以通过使用 this 在实例方法或构造函数内部引用当前对象的任何成员。

没有在那里写的是 this 关键字是可选的,因此这行代码:

salary=s;

和这行代码是等价的:

this.salary=s;

因此它知道要使用哪个实例(在此情况下为 John),因为实际上在 "salary" 前面有一个看不见的 "this",告诉它要赋值给当前对象。

英文:

> 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.

huangapple
  • 本文由 发表于 2020年6月6日 00:46:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/62220324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定