覆盖方法中使用的子类中的变量

时间:2013-10-23 19:54:02

标签: java string class variables

超类:

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类的变量值,为什么这个?

1 个答案:

答案 0 :(得分:1)

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