Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Why can't I declare an array as a simple Object?

In Java, I can compile

Object[] obj = {new Object[1], new Object[2]};

But I cannot compile

Object obj = {new Object(), new Object()};

In the first example I declare a one-dimensional array of Objects and assign it a two-dimensional array. In the second I declare an Object and assign it a one dimensional array.

If a Java array extends Object, why doesn't the second code fragment compile? Why does the first?

like image 428
Student Avatar asked Feb 02 '13 18:02

Student


1 Answers

Assigning an array to an Object isn't a problem, but you have to create the array like this

Object obj = new Object[] { new Object(), new Object[2] };

Otherwise the compiler won't know that it's an Object array and not some other kind of array.

like image 109
Robber Avatar answered Oct 18 '22 18:10

Robber