jav*_*ner 0 java string return return-value
我写了如下简单的代码.基本上setString,我输入"Sentence"作为字符串,在getString它中,它应该返回字符串.当我在Junit中测试时,它表示getString返回null而不是"sentence".
public class MyString implements MyStringInterface{
public String str;
//Sets the value of the current string
public void setString(String str){
str = "Sentence";
}
// Returns the current string
public String getString(){
return str;
}
}
Run Code Online (Sandbox Code Playgroud)
public void setString(String str){
str = "Sentence";
}
Run Code Online (Sandbox Code Playgroud)
在你的代码中,当你打电话时,str = "Sentence" 你实际上正在改变当地的变量.
在您的setString方法中,您将值设置为方法局部变量,而不是实例变量.因此,您的实例变量值不会被更改,它将具有默认值null.您可以按如下方式更改方法
public void setString(String str){
this.str = "Sentence"; // this.str = str;
}
Run Code Online (Sandbox Code Playgroud)
PS
在您的代码中,您将在setter方法中设置修复值.这是一个非常糟糕的做法,你不需要有一个setter来做这样的事情.
| 归档时间: |
|
| 查看次数: |
2256 次 |
| 最近记录: |