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

Array and Reference

 
Bindesh Vijayan
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pls. look at the following code:
class Bird{}
Object obj =new Bird[12]; //1
I dont get compile time error here, why?To me it appears that iam performing an illegal operation cause obj is a reference variable which can hold one reference to type Object.But here Iam assigning 12 object references of type Bird hence an Array.
Next when I add this code I get compile time error
for(int i=0;i<obj.length;i++)
System.out.println(obj.length);
I get an error :No variable length defined in java.lang.Object
Which means I was unable to create an Array Object at 1, right.
So what is the reason for not getting an error at compile time.
Thanks
 
Corey McGlone
Ranch Hand
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JLS, §Arrays:

In the Java programming language arrays are objects (�4.3.1), are dynamically created, and may be assigned to variables of type Object (�4.3.2).

That is why you're not getting a compiler error at line 1. In Java, an array in a descendent of Object and can therefore an Object reference can be assigned a reference to an array.
However, just as with any other case, you are only allowed to invoke the methods on an object as the reference's type understands. Also from that section of the JLS:

All methods of class Object may be invoked on an array.

However, you can't access members of an array from an Object instance. The same goes for any sub/superclass pair. First, you'd need to cast the object, like this:

Instances of Object don't have a length, instances of arrays do. However, you have to tell the compiler that the variable obj really references an array of Brid objects, not an instance of an Object.
I hope that helps,
Corey
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object obj = new Bird[12];

You create an array of 12 Bird objects and assign it (the array) to an Object-type reference. No error there.

However, even though obj is pointing to an array, it is not an array unless you make it

Object obj[] = new Bird[12];

and therefore it will not have a length attribute.

or do what Corey suggested
[ July 17, 2002: Message edited by: Marilyn de Queiroz ]
 
Bindesh Vijayan
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Corey & Marilyn.
It cleared clouds of doubt.
Great Help,Great People, Great Place
Thanks Again
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic