Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

once again instanceof  RSS feed

 
sumit kothalikar
Ranch Hand
Posts: 91
Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the foolowing code:


Even though b is array of class B
It gives compiler error as at line 1
inconvertible types.
found : B{]
required :B

while line2 compiles and runs

I am not getting why it happens .

 
sachin burange
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
b is a list of objects where as B is a class that's why it is giving error.
 
Moguluri Ravi Kiran
Ranch Hand
Posts: 63
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Slightly Modified instance class to understand little more..

 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sumit kothalikar wrote:See the foolowing code:


Even though b is array of class B
It gives compiler error as at line 1
inconvertible types.
found : B{]
required :B

while line2 compiles and runs

I am not getting why it happens .


b is an array and it cannot be instance of class B
here we are not initializing array elements
hence they are pointing to null
as null is not instance of anything
hence b[0] instanceof B[] returns false
and b[0] instanceof Object returns true
if we write
b[0] = new B();
then
b[0] instanceof B returns true
b[0] instanceof Object returns true

hope this is clear to you
Happy coding
 
sumit kothalikar
Ranch Hand
Posts: 91
Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi prasad
will you explain with a code how to use array instance of class in instanceof operator
 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

at line 1 you get error inconvertible types it is explained in the comments above
when you remove or comment line 1 and then run the program
we get the output as follows
C:\Users\Prasad\Desktop>java A
null instanceof Object false
a[0] instanceof A false
a[1] instanceof A true
Done

Hope this is clear to you now
still if you have got problems feel free to ask
happy coding
 
sumit kothalikar
Ranch Hand
Posts: 91
Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it so we can't compare instanceof class arrays with there classes.
Instead we have to intialised them to some class objects
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!