0

I have a class called Occupant and extended Occupant classes for different occupant types such as Animal, Food, Tools, Treasure.

All occupants are placed on GridSquares, A Square can hold up to 3 occupants.

Occupant class has a method to get all the Occupants on a GridSqure when the position is given. The method will return a Occupant Array with extended occupant classes.( E.G: An Animal, A Tool and A Food).

   Occupant[] allOccupants = newGridSquare.getOccupants();

    for ( Occupant oneOccupant : allOccupants)
      {
         if(oneOccupant.getStringRepresentation() == "A")
         {

             player.reduceStamina(oneOccupant.getDanger());

         }
     }

compiler cannot access getDanger method in Animal class just because I already have assigned it as Occupant.

How can I access getDanger method in extended Occupant class Animal?

Michael Gamage
  • 57
  • 1
  • 1
  • 5

2 Answers2

1

You can cast the instance

for ( Occupant oneOccupant : allOccupants)
{
    if("A".equals(oneOccupant.getStringRepresentation()))
    {
        Animal animal = (Animal) oneOccupant;
        player.reduceStamina(animal.getDanger());
    }
}

Assuming the "A" is an identifier for an Animal instance and Animal is a subclass of Occupant and has a getDanger() method. Otherwise, first do a check

if (oneOccupant instanceof Animal) {
     Animal animal = (Animal) oneOccupant;
     player.reduceStamina(animal.getDanger());
}

Related :

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

As getDanger does not exists under Occupant class but in specific class Animal. So you you need to downcast oneOccupant To Animal class .

Another solution is you declare getDanger under Occupant class and implement it under extended class. In case of classes except Animal, you can provide empty implementation. But thats not a good approach from design point of view but sometime is resorted to in case of legacy code

M Sach
  • 33,416
  • 76
  • 221
  • 314