[英]Assigning values to object fields in Java?
For example, if I have this: 例如,如果我有这个:
class Test{
private int id;
public Test(int id){
id=id;
}
}
In this case, how can I assign the value of the id
parameter to the id
field? 在这种情况下,如何将
id
参数的值分配给id
字段?
Use 采用
this.id = id;
because this
refers to the current object. 因为
this
是指当前对象。
Learn more here: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html 在此处了解更多信息: http : //docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Use this
: 使用
this
:
public Test(int id){
this.id = id;
}
Within an instance method or a constructor,
this
is a reference to the current object — the object whose method or constructor is being called.在实例方法或构造函数中,
this
是对当前对象的引用-当前对象正在调用其方法或构造函数。 You can refer to any member of the current object from within an instance method or a constructor by usingthis
.您可以使用
this
从实例方法或构造函数中引用当前对象的任何成员。
您可以使用assign:
this.id = id;
data instance hiding is happening here.your local variable is hiding your instance variable. 数据实例隐藏在这里发生。您的局部变量正在隐藏您的实例变量。 so to access the instance data , always use " this"
因此要访问实例数据,请始终使用“ this”
so this.name=name 所以this.name = name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.