views:

264

answers:

3

Hello everyone,

I need to know which class multidimensional arrays in Java extends exactly?

When we assign

Object[] ref=new int[]{1,2,3};

the compiler complains that the objects are of different types. So it seems that one dimensional arrays extend Object; I know that already.

But when we assign

Object[] ref2=new int[][]{{1,2,3},{4,5,6}};

the compiler will not complain. So it seems that two dimensional arrays extend Object[].

But when I print its superclass name:

System.out.println(ref2.getClass().getSuperclass().getName());

I got java.lang.Object.

So can anyone explain what's going on here?

+12  A: 

A multidimensional array in Java is really just an array of arrays (of arrays)* .

Also, arrays are considered subclasses of Object.

So, your int[][] is an Object[] (with component type int[]), and also an Object (because all arrays are objects)

An int[] however is not an Object[] (but it is still an Object).

So it seems that two dimensional arrays extend Object[]

I am not sure if "extend" is the proper word here. Arrays have a special place in the Java type system, and work a little different from other objects. A two dimensional array is definitely an Object[]. But if you are asking about superclasses, the only superclass that any kind of array has is Object. All arrays are also Cloneable and Serializable.

Thilo
Better phrased than my answer. +1
Michael Myers
@mmyers: +1 for removing your answer in favor of upvoting one you thought was better (or as good and sooner). I wish more of us did that!
T.J. Crowder
If we continue int[][][] is an Object[][], so it is kind a feature in the java language, and there is no Class hierarchy to these arrays.
Skystar3
+3  A: 

Your inheritance tree looks something like this:

  1. ref2 is-a int[][]
  2. ref2 is-a Object[]
  3. ref2 is-a Object

Here's a code fragment that illustrates what I mean:

Object ref2 = new int[][]{{1,2,3}, {4,5,6}};
System.err.println("ref2: " + (ref2 instanceof int[][]) + 
  " " + (ref2 instanceof Object[]));

You should see something like:

ref2: true true
Bob Cross
+1  A: 

Arrays in Java are covariant. This means that TSub[] is a subtype of TSuper[] if TSub is a subtype of TSuper.

You have int[][] which is an array of int[]. Now, as others have pointed out, any array in Java is a subtype of Object, so int[] is a subtype of Object. So, due to array covariance, int[][] is a subtype of Object[] (substitute TSub = int[] and TSuper = Object in the above definition of covariance).

Edit - To make it clear why covariance is important here, consider that doing the same thing with List<T> wouldn't work:

List<Object> ref2 = new List<int[]>()
Ben Lings
-1 your explanation is confusing - `int` does not inherit directly off `Object`
thecoop
I didn't say it did - int[] (array of int) does.
Ben Lings