【问题标题】:Overiding Variables ins subclass used in method覆盖方法中使用的子类中的变量
【发布时间】:2013-10-23 19:54:02
【问题描述】:

超类:

public class question1 {
static Scanner input= new Scanner(System.in);
static int score = 0;
static ArrayList<String> results = new ArrayList<String>();
static String question = "1. Which one of the following is classified as an economic resource? \n A) Consumption \n B) Productivity \n C) Production \n D) Enterprise";
static String answer = "D";

protected void question() {
    System.out.println(question);
    String message = input.nextLine();
            Answer(message);
    }
protected void Answer(String message) {
    if (message.equals("answer")) {
            score++;
            results.add("1." + "Correct\n\n");
            }else{ 
            results.add(question + "\n Incorrect - D\n\n");
            }
    }

public question1() { }

public question1(String newQuestion, String newAnswer) {
    question = newQuestion;
    answer = newAnswer;
    }
}

子类:

public class question2 extends question1 {
String question = "2. Which one of the following is classified as a supply side policy? \n A) A reduction in the rate of interest to reduce inflation \n B) An increase in goverment expenditure on state pensions \n C) A reduction in company taxes to encourage greater investment \n D) A rise in the exchange rate to increase exports";
String answer = "C";

public question2() {
}

public question2(String question, String answer) {
    super(question, answer);
}

}

主要:

public class Paper {
public static void main(String args[]) {
    question1 q1 = new question1();
    question2 q2 = new question2();
    q1.question();
    q2.question();
}
}

当从使用 question2 类创建的 q2 对象调用 question(); 方法时,使用 question1 类中的“answer”和“question”变量值而不是 question2 类中的变量值,为什么会这样?

【问题讨论】:

  • 向我们展示一个示例输出。
  • 你不能覆盖静态成员。
  • 因为您的派生类中没有question() 方法。无论您调用哪个对象question(),它都会打印相同的内容。
  • 那么这是否意味着我必须在派生类中拥有相同的方法副本,它肯定会继承该方法吗?

标签: java string class variables


【解决方案1】:

question2 必须覆盖question() 方法才能使用question2 中声明的字段。 q2.question(); 执行question1 中的实现(由question2 继承,未覆盖),它不知道子类中的字段。

【讨论】:

  • 有没有办法 question2 可以继承 question() 方法,而是使用 question2 中声明的新字段?
  • 没有。子类可以看到超类中的(非私有)字段,但不能看到副类。试想一下,如果你要从超类中删除字段会发生什么。
  • 所以唯一可行的方法是在 question2 子类 aswel 中有方法文本?
  • 我不会重新声明子类中的字段。这不利于代码的可重用性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
相关资源
最近更新 更多