2013-04-06 134 views
0

我有一個叫ChristopherRobinHundredAcreWoodsCharacter的子類)的類,其中有一個叫做FindTail()的方法。非靜態方法不能從靜態上下文中引用?

在另一類Eeyore(子類HundredAcreWoodsCharacter也)中,我想嘗試使用ChristopherRobin中的方法FindTail()。我不知道如何做到這一點。我試圖

if (ChristopherRobin.hasTail()) 

但給我的錯誤:

non-static method hasTail() cannot be referenced from a static context 

如果有人可以幫助將是巨大的,謝謝。

此外,如果值得一提的是,這是在GridWorld(來自AP計算機科學案例研究)完成的。 HundredAcreWoodsCharacterCritter的一個子類。

+3

你調用非靜態方法*在類*,無法完成的事情。您需要先創建一個ChristopherRobin對象,然後調用該對象的方法。 – 2013-04-06 15:58:40

+0

你應該發佈你的代碼爲ChristopherRobin和HundredAcreWoods。 – Thorn 2013-04-06 16:20:19

+0

Google發現了數百個解釋此錯誤消息的項目。你甚至試圖谷歌它? – Vitaly 2013-04-06 16:31:32

回答

1

您正在調用類的非靜態方法,這是無法完成的。您需要先創建一個ChristopherRobin對象,然後調用該對象的方法。

// create the ChristopherRobin object and put in the christopherRobin variable 
ChristopherRobin christopherRobin = new ChristopherRobin(); 

// now call the method on the *object* held by the variable 
if (christopherRobin.hasTail()) { 
    // do something 
} 
+0

對於這個項目,我們必須創建一個跑步者類,其中每個角色的其中一個被創建,那麼你的建議是否仍然有效? – birna 2013-04-06 16:03:06

+0

雖然這會解決編譯錯誤,但它可能不是最好的解決方案。如果它非常簡單,那麼hasTail()方法可能應該是一個靜態方法。實際上,christopherRobin對象可能作爲參數傳遞給被調用的方法或構造函數。 – 2013-04-06 16:03:07

+0

在GridWorld中,Critters存儲在一個集合中並由框架處理。 hasTail可能只需要由這個小動物本身調用。 – Thorn 2013-04-06 16:31:35

0

你可能需要重寫的行爲()或者,因爲這是小動物的子類,覆蓋的,其作用的方法之一()調用。例如,如果具有尾部將影響該小動物可以移動,那麼你會覆蓋getMoveLocations()這裏有一個如何可以使用hasTail一個例子:

//Critters with tails can only move forward. 
public ArrayList<Location> getMoveLocations() { 
    if(this.hasTail()) { 
     ArrayList<Location> listOfOne = new ArrayList<Location>(); 
     listOfOne.add(getLocation.getAdjacentLocation(this.getDirection())); 
     return listOfOne; 
    } 
    else 
     return super.getMoveLocations(); 
} 
相關問題