Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional arrays in Java extends which class?

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?

like image 871
skystar7 Avatar asked Feb 23 '10 16:02

skystar7


3 Answers

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.

like image 170
Thilo Avatar answered Nov 08 '22 05:11

Thilo


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
like image 3
Bob Cross Avatar answered Nov 08 '22 04:11

Bob Cross


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[]>()
like image 2
Ben Lings Avatar answered Nov 08 '22 03:11

Ben Lings