This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
You can test the type of an object at runtime with the operator instanceof:
The Class class also gives you a method:
Or you can use class literals to achieve much the same.
The difference with using class literals is that the test is exact, whereas instanceof and isInstance() are both true if the object compared is of the type of the test or a sub-class of that type. [ May 13, 2005: Message edited by: Paul Sturrock ]
Note that this is one problem solved by overloaded methods. That is, two methods with the same name but different argument types. Consider ...
Now if somebody calls mangle( "String" ) it goes into the first method, but if they call mangle( new Integer(1) ) it goes into the second. The methods document what they accept, there is no "if" test on our part and we can add new methods for new types without touching the existing methods. It's all good.
Look at something like PrintStream in the library and see how many print methods there are. That's how they avoid instanceof.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Originally posted by Stan James: Note that this is one problem solved by overloaded methods.
Also, you may want to consider subclassing when you find yourself using instanceof a lot.
if you have...
...you might consider making VectorThingy and HashtableThingy subclasses. Each of those subclasses would implement xyz(), and then method(), which will still live in the Thingy base class, will just call xyz() and the right functionality will be used.
Of course "instanceof" isn't the only flag that indicates when this should be done. ANY time you see more than one or two if/else that all use the same if condition that doesnt' change through course of a method, you should consider this type of subclassing.
e.g. if (databaseBrand.equals("Oracle")) ... if (currentUser.isAdminUser()) ... if (protocol == Protocols.TCP_IP) ... if (vehicle.class == MOTORCYCLE || vehicle.class == SNOWMOBILE) ...
[EDIT: Added the abstract xyz() to Thingy] [ May 19, 2005: Message edited by: Ryan McGuire ]
Mukherji Sandeep wrote:
Please check it. i and j are not same in this case. But i and j both are still Integer types. so then where is the difference?
They are not the same object. A new one is created for j when you get the intValue(). It is my understanding this basically does new Integer(j.intValue()) behind the scenes. They are meaningfully equivalent and I'm sure if you try .equals() you will see this.
Why reply to such an old thread anywho? In the future i would just create a new one.