You're welcome. But, uh...."searching"? I'm assuming something got lost in translation.
Anyway, why do you think using an interface is not appropriate? Please clarify. Perhaps a case in Java or even PHP might help illustrate your problem.
I think PhiLho's solution answers your question already, and he used different methods on each type of chldren to show an extreme case. The point was that instanceof operator obviates any elaborate scheme for type check. As you have mentioned, overriding .update() is the preferred solution, but the problem in OP was that Parent class does not necessarily have an .update() method.
I suppose use of interface is easier demonstrated than explained. It's a common practice - I'm not demonstrating anything exotic.
Note how instanceof operator is used, like PhiLho's case, but it is used to detect an interface instead of a specific class.
I've also randomized the array to show a case where handcoding a series of object instantiation is not desirable. It also throws the parent class in the mix to show that it does not choke the mass .update() process.
Furthermore, iterator is used to drive home the point that the container is not the problem here, as array, ArrayList, and HashMap all can contain any type of objects.
By the way, you absolutely don't want to use your code where you assign an arbitrary index number to a certain class and assume it to always be the case - that's really asking for trouble further down the road. Keep it simple!
Code:
import java.util.ArrayList;
import java.util.Iterator;
ArrayList listOfObjects;
interface Updatable{
void update();
}
class ParentObj{
ArrayList childobj;
// this can be ArrayList<ParentObj> if you can use generics.
}
class ChildOne extends ParentObj implements Updatable{
void update(){ println("foo");}
}
class ChildTwo extends ParentObj implements Updatable{
void update(){ println("Doh");}
}
void setup()
{
listOfObjects = new ArrayList();
for(int i = 0; i < 20; i++){
float r = random(1);
//println(r);
if(r < 0.2){
listOfObjects.add(new ChildOne());
}else if(r < 0.8){
listOfObjects.add(new ChildTwo());
}else{
listOfObjects.add(new ParentObj());
}
}
Iterator itr = listOfObjects.iterator();
while(itr.hasNext()){
Object obj = itr.next();
if (obj instanceof Updatable){
((Updatable)obj).update();
}
}
}