我想实现一个方法来设置/更改名称。 例如:预设名称是=“Ben”。 用一种方法,应该可以将名称改为=“Charly”。 我的方法到目前为止:
public void setName (String name) { name = ""; }当我调用方法时,我可以输入名称,但我的JDK(blueJ)不保留名称。 我究竟做错了什么? 在此先感谢您的帮助。
I'd like to implement a method to set / change a name. E.g.: preset name is = "Ben". With a method it should be possible to change the name to = "Charly". My approach so far:
public void setName (String name) { name = ""; }When I call the method I can type in the name but my JDK (blueJ) does not keep the name. What am I doing wrong? Thanks in advance for your help.
最满意答案
您只需将代码更改为以下代码(假设您的类中有名为name的引用变量):
public void setName (String name){ this.name = name; }这在Java中称为变量阴影。 例如,当有两个变量(即本地和实例)具有相同的名称时,局部变量优先于实例变量,因此语句如下:
name = "";将值分配给局部变量name而不是实例变量。 为了给实例变量赋值,我们可以使用this关键字(来访问和修改这个值)。
You just need to change the code to the following (assuming you have a reference variable called name in your class):
public void setName (String name){ this.name = name; }This is called Variable Shadowing in Java. E.g. when there are two variables (i.e. local and instance) with the same name, local varialble takes precedence over instance variable and hence, statements like:
name = "";assign the values to local variable name rather than instance variable. To assign value to instance variable, we can use this keyword (to access and modify the value).
如何实现一个java方法来设置用户名(How to implement a java method to set a user name)我想实现一个方法来设置/更改名称。 例如:预设名称是=“Ben”。 用一种方法,应该可以将名称改为=“Charly”。 我的方法到目前为止:
public void setName (String name) { name = ""; }当我调用方法时,我可以输入名称,但我的JDK(blueJ)不保留名称。 我究竟做错了什么? 在此先感谢您的帮助。
I'd like to implement a method to set / change a name. E.g.: preset name is = "Ben". With a method it should be possible to change the name to = "Charly". My approach so far:
public void setName (String name) { name = ""; }When I call the method I can type in the name but my JDK (blueJ) does not keep the name. What am I doing wrong? Thanks in advance for your help.
最满意答案
您只需将代码更改为以下代码(假设您的类中有名为name的引用变量):
public void setName (String name){ this.name = name; }这在Java中称为变量阴影。 例如,当有两个变量(即本地和实例)具有相同的名称时,局部变量优先于实例变量,因此语句如下:
name = "";将值分配给局部变量name而不是实例变量。 为了给实例变量赋值,我们可以使用this关键字(来访问和修改这个值)。
You just need to change the code to the following (assuming you have a reference variable called name in your class):
public void setName (String name){ this.name = name; }This is called Variable Shadowing in Java. E.g. when there are two variables (i.e. local and instance) with the same name, local varialble takes precedence over instance variable and hence, statements like:
name = "";assign the values to local variable name rather than instance variable. To assign value to instance variable, we can use this keyword (to access and modify the value).
发布评论