如何在不用构造函数参数覆盖该变量的情况下获取变量的值?
例如:
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
}
请记住,我不想在 OtherClass 中为构造函数参数硬编码任何内容,并且 changeValues 方法必须保留在 Example 类中。
编辑:我用空格实例化了something变量,然后我提示用户应该将其存储在变量中,然后将其传递给构造函数。现在,我取回了原始实例化空间而不是输入!
你的问题没有多大意义。
-
如果您谈论的是"重写",则构造函数不会被覆盖,因为它们不是继承的。
-
如果您谈论的是用于
Example
"覆盖"something
变量的构造函数,则只需提供一个默认构造函数。 但这不会改变任何东西,因为当你没有显式初始化something
它无论如何都会默认初始化为null
。 事实上,当你用null
参数调用现有构造函数时,它并没有破坏任何东西。
然后我们有你奇怪的changeValues()
方法:
public void changeValues() {
System.out.println("Please change the string! ")
String foo = sc.next();
Example set = new Example(foo);
}
这实际上的作用是:
- 提示用户
- 读取字符串
- 创建一个新的示例实例,然后
- 扔掉!!
您可能应该做的是:
something = sc.next();