aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array Declaration 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 Declaration" Watch "Array Declaration" New topic
Author

Array Declaration

Ram Han
Ranch Hand

Joined: Feb 26, 2002
Posts: 49
Object oa = new boolean[20];

I thought above line should give a compiler error.

But it compiled fine, how ?


SCJP,SCWCD,IBM 285,MCTS
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18988
    
  40

An array is an object. If you like, you can later cast the "oa" object back to a boolean array, and access it.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
vipul patel
Ranch Hand

Joined: Oct 16, 2005
Posts: 146
A very good explanation of this situation can be found from Khalid Mughal.

Look at this hirachy.

Object
|
Object[], int[], char[],boolean[]
|
Foo[]



So any array of primitives is an object and subclass of GodFather java.lang.Object.

Any array of references is an object and subclass of Object[] which is again an object and subclass of Object.

So all following declarations are legal.

Object o = new int[10];
Object o2 = new char[10];
Object o3 = new boolean[10];
Object o1[] = new Foo[10];
o = o1;

I hope it is clear now.
Vlado Zajac
Ranch Hand

Joined: Aug 03, 2004
Posts: 245
Originally posted by dilip agheda:

Any array of references is an object and subclass of Object[] which is again an object and subclass of Object.


(Direct) superclass of any array is Object. Object[] is supertype of any reference array type, but not superclass of it.

(JLS - Class objects for arrays)
[ December 22, 2005: Message edited by: Vlado Zajac ]
 
wood burning stoves
 
subject: Array Declaration