Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof Operator

 
upanshu vaid
Ranch Hand
Posts: 83
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
In this below code the complier error that is coming



Instance_Of_Test.java:7: inconvertible types
found : Bar[]
required: Bar
if(b instanceof Bar)
^
1 error

My ques is why this is so that array object is not passing the instanceof for Bar class but passing for the Object class.
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
upanshu vaid wrote:My ques is why this is so that array object is not passing the instanceof for Bar class but passing for the Object class.

Because the type of b is array of Bar and an array of Bar can never be an instance of Bar so the compiler does not allow it.
All arrays in Java are also Objects so b is an instance of Object.
 
Winston Gutkowski
Bartender
Pie
Posts: 10417
63
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
upanshu vaid wrote:In this below code the complier error that is coming

If that is exactly what you got, then I see your problem, and I sympathise. Classic case of a badly created compiler message.
I suspect if it had said:it would have been a lot clearer.

Unfortunately, compiler writers aren't paid for their language skills; and what seems obvious to them is torture to puny humans like us.

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic