I was wondering how I could handle polymorphism in a for loop without using of “instanceof” like in C#.
Here is what I have :
An abstract class A :
public abstract class A
{
public abstract Map<Long, ? extends A> getNodes();
public abstract void setNodes(Map<Long, ? extends A> n);
}
B and C classes which extends A and implements abstract methods of A :
public class B
{
private Map<Long, C> childNodesC;
@Override
public Map<Long, ? extends A> getNodes()
{
return childNodesC;
}
@Override
public void setNodes(Map<Long, ? extends A> n)
{
for(C child : n)
childNodesC.put(child.getId(), child);
}
}
Is a for-loop like this one in setNodes() method, possible in Java ? I mean, is there a way for Java to understand that, in my loop, I want to iterate only over all C objects in a list of A objects (which here could be either B or C objects).
Or maybe I don’t use polymorphism in the right way or something like that…or maybe this is a true case of “instanceof” operator usage 🙂
(Yeah you’re right, I don’t like “instanceof” operator, it makes me think that I didn’t do the things correctly so I need to fix them with casts and instanceof. It looks “dirty” to me, but maybe I’m wrong and it is very common to use it !)
Thanks !
There are sometimes cases where you need to know of which subclass an instance is. We can’t really determine if your case is one of those. But if you need to implement this you should consider using the Visitor Pattern and only implement the method of your wanted subclass. This way you avoid the ‘dirty’ instanceof checks.