[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

determining the type of an object

Posted on 1998-11-05
1
Medium Priority
?
229 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 200 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

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…
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 …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

873 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