Reputation: 8526
I haven't written any Java code in more than 10 years. I'm enjoying it, but I don't think I get some of the details of polymorphic programming. I have an abstract Node class, which has tag and data subclasses (among others), and I store them in an ArrayList.
But when I get them out of the ArrayList via an Iterator, I get Node objects back. I'm not sure how best to deal with the objects I get back from the iterator.
Here's an example:
// initialize the list
TagNode tag = new TagNode();
ArrayList<Node> list = new ArrayList<>();
list.add(tag);
// And many more go into the list, some TagNodes, some DataNodes, etc.
and later I use an iterator to process them:
Iterator<Node> i = list.iterator();
Node n = i.next();
// How do I tell if n is a TagNode or a DataNode?
I know that I can cast to one of the Node subclasses, but how do I know which subclass to use? Do I need to embed type information inside the Node classes?
Upvotes: 0
Views: 179
Reputation: 759
The polymorphic behavior would mean that you don't really care if you know what type of Node
is it. You just simply call the API and the behavior will as per the implementation of concrete type.
But if you really need to know, one of the ways is to use instanceof
to know which is the exact type. For e.g.
if( i instanceof tag )
// handle tag
else if( i instanceof data)
//handle data
Upvotes: 0
Reputation: 621
As others said, checking explicitly which subclass your object belongs to should not be necessary and is also a bad style. But if you really need it, you can use instanceof
operator.
Upvotes: 0
Reputation: 2698
Ideally you don't want to treat them differently, but if you wanted to determine the type, you can check using instanceof:
Node n = i.next();
if (n instanceof Tag) {
// behavior
}
Upvotes: 1
Reputation: 48444
You should not need to know which child class is which, in most circumstances.
That is precisely the advantage with polymorphism.
If your hierarchical design is solid, the Node
will have all the behaviors (== methods) needed to perform operations on your List
items without worrying about which child class they are an instance of: overridden methods resolve at runtime.
In some cases, you might want to use the instanceof
operator to actually check which child class
your Node
belongs to, but I would consider it a rare case, best to be avoided in general principles.
Upvotes: 5