I am having troubles with the instanceof
operator. I'm trying to avoid it. Basically, I have the following structure:
class Shape {}
class Triangle extends Shape {}
class Rectangle extends Shape {}
ShapeParser s;
while (s.hasNext())
parseShape(s.next()); // returns a Shape object
void parseShape(Triangle t) { // do stuff } // KEY POINT HERE
void parseShape(Rectangle t) { // etc }
The key point I'm making is: I want to do a parameter overload of the function, but it's not working as I intend it to (compile-error). I am trying to avoid:
void parseShape(Shape s)
{
if (s instanceof Triangle) ...
}
UPDATE: it seems that the consensus is to create a base class method: parseShape() to do the lifting. I wanted to clarify my question: the motivation of this question is relative to the observer pattern. Suppose I have the following Observer object payload method:
public void update(Observable obj, Shape objectPayload){}
// note: the objectPayload is usually of type Object
Instead of performing:
public void update(Observable obj, Shape objectPayload)
{
if (objectPayload instanceof Triangle)
// do stuff
else if (objectPayload instanceof Rectangle)
// etc
}
I want to do:
public void update(Observable obj, Shape objectPayload)
{
parseShape(objectPayload);
}
void parseShape(Triangle t) { } // do stuff
void parseShape(Rectangle t) { }