父類中使用亞類:Overiding變量INS在方法
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();
方法是從Q2對象調用使用所創建的question2類使用question1類中的'answer'和'question'的變量值來代替那些來自question2類的人,爲什麼會這樣呢?
向我們展示一個示例輸出。 – Prateek
您不能重載靜態成員。 – clcto
因爲你的派生類沒有'question()'方法。無論你用哪個對象調用'question()',它都會打印同樣的東西。 – Prateek