-1

How come I can assign an array to an object reference

Object x = (Object) new int[] { 1, 2, 3 };// no error
Object y = new int[] { 1, 2, 3 };//no error

Do java arrays inherit from Object similar to classes?

I expected this to give me a compile time error.

Doing this:

System.out.println(x.toString() + " " + x.getClass().getName() + " " + x.getClass().getTypeName());

Results in:

[I@15db9742 [I int[]
Diaa
  • 869
  • 3
  • 7
  • 19

3 Answers3

3

According to official tutorial :

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

solar
  • 1,344
  • 1
  • 8
  • 14
2

Do java arrays inherit from Object similar to classes?

Yes, because arrays are instances of classes, just like other objects. This is why they have hashCode and toString and getClass, they inherit them from Object.

From JLS§10.1:

The supertype relation for array types is not the same as the superclass relation. The direct supertype of Integer[] is Number[] according to §4.10.3, but the direct superclass of Integer[] is Object according to the Class object for Integer[] (§10.8). This does not matter in practice, because Object is also a supertype of all array types.

(my emphasis)

And (perhaps relevant) from JLS§10.2:

A variable of array type holds a reference to an object.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Well all arrays(primitive arrays or Object arrays) are Objects.

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35