• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Declaration

 
Ram Han
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object oa = new boolean[20];

I thought above line should give a compiler error.

But it compiled fine, how ?
 
Henry Wong
author
Marshal
Pie
Posts: 21005
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An array is an object. If you like, you can later cast the "oa" object back to a boolean array, and access it.

Henry
 
vipul patel
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic