0

というメソッドがあるChristopherRobin(のサブクラス)というクラスがあります。HundredAcreWoodsCharacterFindTail()

別のクラスEeyore(のサブクラス) で、 のメソッドをHundredAcreWoodsCharacter試して使用したいと考えています。これを行う方法がわかりません。私は試したFindTail()ChristopherRobin

    if (ChristopherRobin.hasTail())

しかし、それは私にエラーを与えます:

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

誰かがそれを助けることができれば、ありがとう。

GridWorldまた、これが(AP コンピューター サイエンスのケース スタディから)で行われていることに言及する価値がある場合。HundredAcreWoodsCharacterのサブクラスですCritter

4

2 に答える 2

1

classで非静的メソッドを呼び出していますが、これは実行できません。最初に 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
}
于 2013-04-06T16:00:09.977 に答える
0

おそらく act() をオーバーライドするか、これは Critter のサブクラスであるため、act() が呼び出すメソッドの 1 つをオーバーライドする必要があります。たとえば、尻尾を持つことがこの Critter の動きに影響する場合は、オーバーライドします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();
} 
于 2013-04-06T16:29:55.860 に答える