-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[]
0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.