2013-04-06 133 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(); 
} 
相关问题