Eduardo
Eduardo

Reputation: 7121

Overloading with Polymorphism

I'm designing a physics simulator with 3 types of things that can collide.

The most basic [abstract] class is called Item which contains information on mass, position & speed.

There are 3 other types: Circle, Boundary & Photon which extend the Item class and have their own properties.

I have a List<Item> called system which contains various Circles, Boundaries etc and I go through this list to check for collisions by using a method: system.get(i).collide(system.get(j)); and this edits the velocities etc.

My problem is, Eclipse wants me to have a method in each of the Circle, Boundary... classes called collide(Item itemName) but by doing this the compiler wouldn't be able to treat each type of item differently.

I currently have different methods in the Circle, Boundary... classes like:

collide(Circle c){..}
collide(Boundary b){..}
collide(Photon p){..}

But the compiler wants a general collide(Item i) method.

How can I satisfy the compiler but still treat collisions with different types differently using inheritance the way I have?

Upvotes: 0

Views: 81

Answers (3)

kiruwka
kiruwka

Reputation: 9450

You should Override collide(Item i) for each of subclasses. You could check the type of item in each implementation, for instance, in your Photon class :

@Override
public void collide(Item item) {
    if (item instanceof Photon) {
         // implement collision of this with (Photon) item
    } else if ... {
        // I wonder how collision of Photon with Circle would look like :)
    }
}

This is quite similar approach to Overriding Object's equals method for new types.

Upvotes: 3

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

You can simply keep collide(Item b){..} or Something like collide(<? extends Item> b){..}. You can introduce generics concept here if you are going to pass subtypes also. This will give more info about it. http://www.thejavageek.com/tag/generics/

Upvotes: 1

Matthew Wilson
Matthew Wilson

Reputation: 2065

You can still use collide(Item i)

But if you want the method to act differently for each super class you can do this:

public void collide(Item i) {

    if(i instanceof Circle) { 
      //do something for a circle
    } else if(i instanceof Photon) {
      //do something for a photon
    } else if(i instanceof Boundary) {
      //do something for a boundary
    }
}

Upvotes: 2

Related Questions