overexchange
overexchange

Reputation: 1

Why are we able to assign arrays to reference of type Object in Java?

As part of learning, here is the pathological example below that am trying to understand,

class C{}; interface I{}; class S extends C implements I{};
class B{};

With these declarations, I can say that, class C class B are immediate subclass of Object class and can access all methods of Object class from within those classes. But,

1) When i declare interface I{}; How is interface I related to Object class?

In continuation, Below are some assignment to array types, followed by subclass to super class assignment and vice-verse.

C[] c = new C[4];
S[] s = new S[6];
I[] i = new S[0];
B[] b = new B[2];

//i = new C[2]; Compile error
i =s; c=s; s = (S[])c; i = (I[])c;
i = (I[])b;  //Run-time error

I learnt that arrays are 'first class objects' and immediate subclass of Object class,

Object o = c;  // i mean `I i = c;` will not work `I[] i =c;` works 

2) With respect to above definition(syntax), What is the meaning of 'arrays are first class objects'?Because Object[] oa = c; make sense to me as class C is immediate subclass of Object class.

Upvotes: 4

Views: 215

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36649

When i declare interface I{}; How is interface I related to Object class?

From the Java Language Specification:

If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

How would i consider reference variable o pointing to array c

As stated in the comments, the array is itself a subclass of Object, so the following assignment is valid:

Object o = c;

The relevant part from the Java Language Specification says:

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).

This is also what is meant by "arrays are first class objects". In Java, an array is not a special type or some special construct - it is essentially a sub class of Object with additional fields (in particular length) (and some additional compiler support to be able to syntactically describe and initialize an array).

Upvotes: 4

Related Questions