0

超类:

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();
}
}

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

4

1 回答 1

1

question2必须重写该question()方法以使用在 中声明的字段question2q2.question();执行question1(由 继承question2,不被覆盖)中的实现,它不知道子类中的字段。

于 2013-10-23T20:03:02.687 回答