如何在不使用构造函数参数覆盖该变量的情况下获取变量的值?
例如:
public class Example {
String something = "";
Scanner sc = new Scanner(System.in);
public Example()
{
}
public Example(String something){
this.something = something;
}
// Getter method
public String getSomething() {
return something;
}
public void changeValues() {
System.out.println("Please change the string!");
something = sc.next();
Example set = new Example(something);
}
}//example
public class AnotherClass {
Example test = new Example()
// I don't want to overwrite this so I set this to null
String something2 = test.getSomething();
// the above puts in a null reference instead of the text
}
请记住,我不想在 AnotherClass 中为构造函数参数硬编码任何内容,并且 changeValues 方法必须保留在 Example 类中。
编辑:我用空格实例化了 something 变量,然后我提示用户应该将其存储在变量中,然后将其传递给构造函数。现在,我取回了原始的实例化空间而不是输入!