• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance of "Object" class

 
Saeed Amer
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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))
...
 
Saeed Amer
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great! Thank you so much!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic