Solved

determining the type of an object

Posted on 1998-11-05
1
184 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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now