Why isn't there a java.lang.Array class? If a java array is an Object, shouldn't it extend Object?

From JLS:

Every array has an associated Class object, shared with all other arrays with the same component type. [This] acts as if: the direct superclass of an array type is Object [and] every array type implements the interfaces Cloneable and java.io.Serializable.

This is shown by the following example code:

class Test {
    public static void main(String[] args) {
        int[] ia = new int[3];
        System.out.println(ia.getClass());
        System.out.println(ia.getClass().getSuperclass());
    }
}

which prints:

class [I
class java.lang.Object

where the string "[I" is the run-time type signature for the class object "array with component type int".

And yes, since array types effectively extend Object, you can invoke toString() on arrayObject also see the above example

int arr[] = new arr[2];
arr.toString();

Arrays are a language feature - they have a specific syntax for declaring and accessing. And their class definition is hidden from you.

They have a representation in the refleciton API - java.lang.reflect.Array

Btw, the length field is not inherited from Object. The .getClass(), .toString(), etc. methods are inherited.


Slight elaboration of the above code segment:

public class ClassForName {
    public static void main(String[] argv) throws ClassNotFoundException {
        Class theClass = Class.forName("[I");
        System.out.println(theClass.getName());
        Class superClass = theClass.getSuperclass();
        System.out.println(superClass.getName());
    }
}

Results:

C:\JavaTools>java ClassForName
[I
java.lang.Object

As can be seen, "[I" is the name of the class which we would call, in English, "array of int". The class is a "full citizenship" Java class, which responds to all the methods of Object. The only difference is that the new syntax is different and it doesn't support the newInstance() method of Class.

(The classes "[I", "[C", et al, are "pre-defined" in the JVM -- there are no .class files corresponding to them. Java also will implicitly create, on the fly, the "[MyJavaClass;" class if you have an array of "MyJavaClass" in your program.)