gpt4 book ai didi

java - 重写方法中使用的子类中的变量

转载 作者:行者123 更新时间:2023-12-01 13:57:29 24 4
gpt4 key购买 nike

父类(super class):

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类,这是为什么?

最佳答案

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

关于java - 重写方法中使用的子类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19551073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com