This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Instance of Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Instance of "Object" class" Watch "Instance of "Object" class" New topic
Author

Instance of "Object" class

Saeed Amer
Ranch Hand

Joined: Jan 20, 2004
Posts: 140
Why can we not use object of Object class as on line "6" in the code below:

1: public class Test2{
2: public static void main(String[] args) {
3: Dummy x ;
4: x = new Dummy();
5: Object b = new Object();
6: if (x instanceof b)
7: System.out.println("instanceof");
8: }
9: }
10:
11: lass Dummy {
12: }

TIA
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Because the right-hand operand of "instanceof" is the name of a class, not any kind of variable or other data.

If you want to determine if an object is an instance of a class determined dynamically, use the "isInstance()" method in java.lang.Class:

3: Dummy x = new Dummy();
5: Object b = new Object();
6: if (b.getClass().isInstance(x))
...


[Jess in Action][AskingGoodQuestions]
Saeed Amer
Ranch Hand

Joined: Jan 20, 2004
Posts: 140
Great! Thank you so much!!
 
wood burning stoves
 
subject: Instance of "Object" class
 
Similar Threads
How to get a base class subobject
instanceof question
When will instanceof return false
Instanceof.
Khalid Mughal and instanceof operator