我写了如下简单的代码。基本上在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;
}
}
最佳答案
public void setString(String str){
str = "Sentence";
}
在代码中,当您调用 str = "Sentence"
时,您实际上是在更改本地变量。
在您的 setString
方法中,您将值设置为方法局部变量,而不是实例变量。所以你的实例变量值不会改变,它的默认值为空。
您可以按如下方式更改方法
public void setString(String str){
this.str = "Sentence"; // this.str = str;
}
附注
在您的代码中,您正在 setter 方法中设置固定值。这是一种非常糟糕的做法,您不需要有一个 setter 来做这样的事情。
关于Java 代码返回 null 而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25656426/