wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array and Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array and Reference" Watch "Array and Reference" New topic
Author

Array and Reference

Bindesh Vijayan
Ranch Hand

Joined: Aug 21, 2001
Posts: 34
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

Joined: Dec 20, 2001
Posts: 3271
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


SCJP Tipline, etc.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9046
    
  10
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 ]

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Bindesh Vijayan
Ranch Hand

Joined: Aug 21, 2001
Posts: 34
Thanks Corey & Marilyn.
It cleared clouds of doubt.
Great Help,Great People, Great Place
Thanks Again
 
GeeCON Prague 2014
 
subject: Array and Reference