Okay, suppose I have a class A and subclasses B, C, D, E, F, G. I have a function:
public void foo (A object)
I have the default function handler which handles A objects which aren't subclassed, and the B, C, and D subclasses. Subclasses of type E, F, G have special needs, so there are functions for them, so four functions altogether:
public void foo (A object)
{
// handle when object is not of type E, F, G
}
public void foo (E object)
{
// handle when object isof type E
}
public void foo (F object)
{
// handle when object is of type F
}
public void foo (G object)
{
// handle when object is of type G
}
These functions are all in the A class. Function call is this:
A a = new A ();
A e = new E ();
a.foo (e);
The function that needs to get implemented is the function foo that takes a parameter of type E. The above function call goes to the function that takes a parameter of type A. In the function that takes a parameter of type A, I can do this to redirect it:
public void foo (A object)
{
if (object instanceof E)
foo ((E) object); // typecast to type E
else if (object instanceof F)
foo ((F) object); // typecast to type F
else if (object instanceof G)
foo ((G) object); // typecast to type G
else
{
// code to handle the other cases
}
}
Is there a better way? There are actually many more than three subclasses that need the special handling, so that's a long if-else if-else statement.