Assuming I create a method which is passed an object and that method would perform an action depending on the object passed. How should I identify the object?
I thought of using the class name to identify the object, but that may be impractical since I could easily change the class name of objects, and generate headaches during future development. Am I right?
edit: for example, i have objects ball and bomb. if i have another object called wall, and the wall has the method to resolve collisions with the wall (e.g. the coordinates of the colliding ball and bomb) but have different logic depending on the colliding object (i.e. ball and bomb)
What you are asking for is the
instanceofoperator.However, this is not a good practice. Instead you may use the so called double-dispatch. Make the object that is passed conform to an interface which defines the operation in terms of the other class. So:
And then provide the appropriate implementations within
BallandBomb(both of which implementThrowableItem)Take a look at the Visitor pattern – you can move the operations to a
WallVisitorwhich knows how to handle the colisions for each object.