2013-10-23 36 views
0

父類中使用亞類: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類的人,爲什麼會這樣呢?

+0

向我們展示一個示例輸出。 – Prateek

+0

您不能重載靜態成員。 – clcto

+0

因爲你的派生類沒有'question()'方法。無論你用哪個對象調用'question()',它都會打印同樣的東西。 – Prateek

回答

1

question2必須重寫question()方法以使用question2中聲明的字段。 q2.question();執行question1中的實現(由question2繼承,未覆蓋),它不知道子類中的字段。

+0

有沒有辦法question2可以繼承question()方法,但使用question2中聲明的新字段? –

+0

否。子類可以看到超類中的(非私有)字段,但不能副字。試想一下,如果你要從超類中移除字段會發生什麼。 –

+0

所以這個工作的唯一方法是讓question2子類中的方法文本aswel? –