1

Projectiles is a arrayList of Projectile. There are a couple subClasses of Projectile like Laser. Here im trying to pass a Projectile into another function.

  void checkProjectiles() {

    for (int index=0; index<Projectiles.size (); index++) {
      if (sq(Projectiles.get(index).xPos - posX) + sq(Projectiles.get(index).yPos - posY) < sq(size)) { //if within the a circle radius of size from centre of roid
        Projectile checkProjectile = Projectiles.get(index);
        collision(checkProjectile);
      }
    }
  }

My problem is that when passing an instance of Laser into this function, instead of going to collision(Laser laser) it goes to collision(Projectile projectile) instead. How do I get the object to pass as an instance of its specific subClass?

Andrew
  • 15
  • 3
  • Can you have a collision method for the base class and override it in sub class. This way, whatever sub class object you passed in will call the corresponding collision method – dragon66 Nov 17 '14 at 15:03
  • @dragon66 This is what I actually would have liked to do. But im doing this as a class assignment and the lecturer insisted we use an overloaded method to handle this event. He told me to look up 'the visitor dilema' – Andrew Nov 17 '14 at 19:13
  • Anyway, the way the answer suggested will be a maintenance nightmare when you are going to add more sub class type to it. – dragon66 Nov 17 '14 at 19:22

1 Answers1

1

The problem you are having is that, as far as the program is concerned, everything in Projectiles can only be resolved as a Projectile, not as any of its subclasses. There are a few ways to handle this, but the simplest, I think, is to handle it within collision. Expect to be handed a Projectile type object and split it out within the method using the instanceof method.

See this answer for an example of comparison operators with class types. Check if an object belongs to a class in Java

You should read up on Polymorphism and things like Interfaces, which can also be useful.

Community
  • 1
  • 1
Marshall Tigerus
  • 3,675
  • 10
  • 37
  • 67