非静态方法不能从静态上下文中引用?
问题描述:
我有一个叫ChristopherRobin
(HundredAcreWoodsCharacter
的子类)的类,其中有一个叫做FindTail()
的方法。非静态方法不能从静态上下文中引用?
在另一类Eeyore
(子类HundredAcreWoodsCharacter
也)中,我想尝试使用ChristopherRobin
中的方法FindTail()
。我不知道如何做到这一点。我试图
if (ChristopherRobin.hasTail())
但给我的错误:
non-static method hasTail() cannot be referenced from a static context
如果有人可以帮助将是巨大的,谢谢。
此外,如果值得一提的是,这是在GridWorld
(来自AP计算机科学案例研究)完成的。 HundredAcreWoodsCharacter
是Critter
的一个子类。
答
您正在调用类的非静态方法,这是无法完成的。您需要先创建一个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
}
答
你可能需要重写的行为()或者,因为这是小动物的子类,覆盖的,其作用的方法之一()调用。例如,如果具有尾部将影响该小动物可以移动,那么你会覆盖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();
}
你调用非静态方法*在类*,无法完成的事情。您需要先创建一个ChristopherRobin对象,然后调用该对象的方法。 – 2013-04-06 15:58:40
你应该发布你的代码为ChristopherRobin和HundredAcreWoods。 – Thorn 2013-04-06 16:20:19
Google发现了数百个解释此错误消息的项目。你甚至试图谷歌它? – Vitaly 2013-04-06 16:31:32