2011-05-08 69 views
0

我想知道爲什麼我的子類沒有正確繼承。繼承方法不工作從父類

如果我有...

public class ArithmeticOp{ 

    //some constructor 

    public static void printMessage(){ 
     System.out.println("hello"); 
    } 

} 

和其他類

public class AddOp extends ArithmeticOp{ 

    //some constructor 

    ArithmeticOp op = new ArithmeticOp(); 
    op.printMessage();   //returns error 
} 

我的日食持續返回 「語法錯誤令牌 」printMessage「,標識預計令牌之後」

有人可以幫忙嗎?謝謝!有沒有其他方法可以從父類調用方法以及從子類調用?謝謝一堆!

+0

您的代碼片段是否準確?我以爲你會做ArithmeticOp op = new AddOp();無論哪種方式靜態方法總是屬於類,而不是對象。所以繼承不會與靜態工作。我想你想放棄static關鍵字並使用OOP。在調用靜態方法時,總是需要調用Class, ArithmeticOp.printMessage(),不在實例上調用,例如op.printMessage(); – planetjones 2011-05-08 13:58:04

回答

3

這是因爲你不能把任意代碼到類體:

public class AddOp extends ArithmeticOp{ 

    ArithmeticOp op = new ArithmeticOp(); // this is OK, it's a field declaration 
    op.printMessage();     // this is not OK, it's a statement 
} 

op.printMessage();需要是一個方法的內部,或內部的初始化塊。

那邊,你的代碼感覺不對。爲什麼你想要在裏面實例化一個ArithmeticOp它自己的子類之一?

+0

哦,它比我想象的更基礎。 + 1用於完全讀取編譯器錯誤! – planetjones 2011-05-08 14:00:05

+0

@planetjones:我也看不到它,我不得不啓動Eclipse來發現它:) – skaffman 2011-05-08 14:01:25

+0

我明白了!謝謝一堆! – Sasha 2011-05-08 23:13:45

0

這是因爲該方法被聲明爲靜態。我可能是誤會,我敢肯定,如果我會有人發表評論,但我認爲你可以這樣做:

public class AddOp extends ArithmeticOp{ 

    //some constructor 

    ArithmeticOp op = new ArithmeticOp(); 
    super.printMessage();   //super should call the static method on the parent class 
} 

或者

public class AddOp extends ArithmeticOp{ 

    //some constructor 

    ArithmeticOp op = new ArithmeticOp(); 
    ArithmeticOp.printMessage();   //Use the base class name 
} 
+0

-1沒有,仍然不能編譯(見其他答案)。 – skaffman 2011-05-08 13:59:32

+0

感謝您的幫助!它只是需要在一個函數內部也可以調用該語句 – Sasha 2011-05-08 23:14:15