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

question2 クラスを使用して作成された q2 オブジェクトからメソッドが呼び出されると、question();question2 クラスの変数の代わりに、question1 クラスの「answer」および「question」の変数値が使用されます。これはなぜですか?

4

1 に答える 1

1

question2question()で宣言されたフィールドを使用するには、メソッドをオーバーライドする必要がありますquestion2。サブクラスのフィールドを認識しない( によって継承され、オーバーライドされない) でq2.question();実装を実行します。question1question2

于 2013-10-23T20:03:02.687 に答える