Solved

determining the type of an object

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This video teaches viewers about errors in exception handling.

920 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

16 Experts available now in Live!

Get 1:1 Help Now