简体   繁体   English

访问扩展类方法

[英]Access extended class method

I have a class called Occupant and extended Occupant classes for different occupant types such as Animal, Food, Tools, Treasure . 我有一个名为Occupant extended Occupant classes ,并针对不同的乘员类型(例如Animal,Food,Tools,Treasure) extended Occupant classes

All occupants are placed on GridSquares , A Square can hold up to 3 occupants . 所有乘员都放在GridSquares ,一个Square最多可容纳3名乘员

Occupant class has a method to get all the Occupants on a GridSqure when the position is given. 占用者类具有一种方法可以在指定位置时获取GridSqure上的所有占用者 The method will return a Occupant Array with extended occupant classes.( EG: 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. 编译器无法访问Animal类中的getDanger方法,因为我已经将其分配为Occupant。

How can I access getDanger method in extended Occupant class Animal ? 如何在扩展的乘员类Animal中访问getDanger方法?

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. 假设"A"是用于标识Animal实例和动物是的一个子类Occupant并且具有getDanger()方法。 Otherwise, first do a check 否则,先检查一下

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

Related : 相关:

As getDanger does not exists under Occupant class but in specific class Animal. 因为getDanger在Occupant类下不存在,但在特定的Animal类中。 So you you need to downcast oneOccupant To Animal class . 因此,您需要将oneOccupant To Animal类降级。

Another solution is you declare getDanger under Occupant class and implement it under extended class. 另一个解决方案是在Occupant类下声明getDanger并在扩展类下实现它。 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 但是,从设计的角度来看,这并不是一个好的方法,但是在遗留代码的情况下,有时会采用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM