Solved

determining the type of an object

Posted on 1998-11-05
1
219 Views
Last Modified: 2010-03-30
Ok, here's my problem...
i've built a tree and now i'm walking down the tree and trying to extract values from the objects as i walk down it.
But my problem is that the method i call depends on the type of the object.  I would have to call intValue() if the object was of type Constant in my program b/c this type would contain an object Integer and i would charValue() if the type was Variable in my program b/c this would contain a Character.  Both Constant and Variable have a parent class called ETree.  How do I deterine what type of ETree i am looking at as I walk down the tree???
thanks!
0
Comment
Question by:wazila
1 Comment
 
LVL 16

Accepted Solution

by:
imladris earned 50 total points
ID: 1227012
You can use the instanceof operator. This is a Java keyword that takes an object and a class name, and results in true or false. So you could use it something like:

ETree object;

if(object instanceof Constant)i=intValue();
else if(object instanceof Variable)i=(int)charValue();



Alternatively, you could define an interface that each class implements so that you can call the same method, regardless of class type, that returns something appropriate. I don't know whether that is possible in your program, but it would be OOPier. Too much instancof'ing is frowned upon.

0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question