Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why can't we use the IS-A test for the enhanced for-loop?

 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a sample from the K&B book (p 559), with a little addition:



I get a compiler error (incompatible types) for this line:

for (Integer o : oa)

If I change it to for (Object o : oa), it's working fine. Integer IS-A Object but how come it is not applicable here?
 
Keith Nagle
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Denise Saulon:
This is a sample from the K&B book (p 559), with a little addition:



I get a compiler error (incompatible types) for this line:

for (Integer o : oa)

If I change it to for (Object o : oa), it's working fine. Integer IS-A Object but how come it is not applicable here?


I would imagine that you are getting the compiler error here because if may be possible that you will try to invoke methods using the Integer reference variable (such as o.intValue()) that Object class cannot do.
Consider that an array of Objects is returned when you invoke
even though you
know that it's an array of Integers. The array is only constructed at run time so at compile time the compiler wont know what the actual array type will be.
Regards
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If I change it to for (Object o : oa), it's working fine. Integer IS-A Object but how come it is not applicable here?


You're telling the compiler you have an array of Objects. Next you're saying 'and with the Integer objects in the array, I'll....'. The compiler disagrees, because Object IS-NOT-AN Integer.
 
Arie Prastowo
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is the same as this
Object o=new Integer(5);
Integer i=o; //--> will not compile
 
Madhukar Ojha
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rancher



Because referenc type of oa is Type Object[] .
Hence return type of object is of type is Object.

You are trying to hold the reference type of super class in sub type .

You can o like this


I hope it will help you.
 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was confused . But at least now I got it. I must have interpreted it as Integer IS-A Object but it's really the other way around.

I appreciate so much your replies guys. Thank You!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic