0

I had a number of classes which extended an abstract class. Each of these classes could be returned in a 'set' by a method elsewhere in the project.

public abstract class AbstractBuilding{
    ....
}

public class ABuilding extends AbstractBuilding{
    ....
}     

In another class:

World world = worldManager.getWorld();   
   for (AbstractBuilding building : world.getBuildings()){
       if (building.toString().contains("SomeSequence")){
            //Do Something
       }
    }

Where world.getBuildings() returns a set of all Abstract Buildings/classes.

Due to design changes, ABuilding is now an Abstract Class itself in addition to extending the original AbstractBuilding. And more classes extend from ABuilding.
Note: I still have other regular classes which extend AbstractBuilding as before - ABuilding2

public abstract class AbstractBuilding{
    ....
}
public class ABuilding2 extends AbstractBuilding{
    ....
}

public abstract class ABuilding extends AbstractBuilding{
    ....
}

public class TheBuilding extends ABuilding{
    ....
}

When I call the world.getBuildings method now, I still get the set of all abstract buildings, which include buildings such as TheBuilding as it extends ABuilding which itself extends AbstractBuilding.

Is there some way that I can identify if a building in the returned set of buildings extends from this new abstract building?

Dan
  • 448
  • 7
  • 18
  • It's really unclear what you're asking, but perhaps you're just looking for `instanceof`? – Jon Skeet Oct 15 '15 at 23:22
  • Specifically, `if (building instanceof ABuilding) ...` – xathien Oct 15 '15 at 23:23
  • 1
    The [Visitor](https://sourcemaking.com/design_patterns/visitor) pattern is typically recommended in this type of scenario. – jaco0646 Oct 15 '15 at 23:26
  • 3
    You need `instanceof`, which means you should refactor until you don't. – sqykly Oct 15 '15 at 23:26
  • `instanceof` does do what I want but the whole design pattern doesn't seem to be 'efficient'/correct. @jaco0646, I think this what I am looking for. – Dan Oct 15 '15 at 23:29
  • It seems that I will use `instanceof` and look into better ways of structuring scenario's such as this in the future – Dan Oct 15 '15 at 23:31
  • Also, you should consider _composing_ the building from (loosely-coupled) components, instead of _inheriting_ from many layers of abstract base classes. See also [Prefer composition over inheritance?](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) – Mick Mnemonic Oct 15 '15 at 23:33

0 Answers0