覆盖构造函数参数

时间:2012-12-14 05:11:53

标签: java constructor

如何在不使用构造函数参数覆盖该变量的情况下获取变量的值?

例如:

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类中。

编辑:我用空格实例化了某个变量,然后我提示用户应该将其存储在变量中,然后将其传递给构造函数。现在,我回到原来的实例化空间而不是输入!

1 个答案:

答案 0 :(得分:0)

你的问题没有多大意义。

  • 如果您正在谈论“覆盖”,则不会覆盖构造函数,因为它们不会被继承。

  • 如果您正在讨论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);
}

实际所做的是:

  1. 提示用户
  2. 读取字符串
  3. 创建一个新的Example实例,然后
  4. 扔掉它!!
  5. 你应该做的是:

        something = sc.next();
    
相关问题