overexchange
overexchange

Reputation: 1

Is array size irrelevant in java?

As per the below statement,

An array of subclass may be assigned to an array of its superclass. An array of implementing class may be assigned to an array of its interface type. Size is irrelevant.

I wrote below sample code to check the behavior of size in array

interface I{}
class C implements I{}

/* dummy.java*/
public class dummy{
    public static void main(String[] args){
        C[] c = new C[6];
        I[] i = new I[2];
        c[0] = new C();
        c[1] = new C();
        c[2] = new C();
        c[3] = new C();
        c[4] = new C();
        c[5] = new C();
        i = c;
        System.out.println(i[5].getClass());
    }
}

When i say, new C[6];, an object [null,null,null,null,null,null] gets created of type class [LC and c points to this object. When i say, new I[2];, an object [null,null] gets created of type class [LI and i points to this object.

My question:

How interface array is working here, when i say i[5], despite an object [null, null] being created after defining new I[2]? What exactly is happening when i say i = c;? Is size of array of interface new I[2]; getting modified during assignment i = c;?

Upvotes: 1

Views: 75

Answers (2)

shinjw
shinjw

Reputation: 3431

When you set i=c

You are setting i to point to the object created by c. Therefore, i will now point to C[6]; < this array

So... i[1] = new I(); c[1] will return a I object

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280000

What that quote is trying to say is that the size of an array is part of the object, ie. it is not part of the reference or the variable type.

In

i = c;

you are assigning a copy of the value of the reference held in c to i. That is, i will reference the same instance as c.

Is size of array of interface new I[2]; getting modified during assignment i=c;?

No, that's the whole point. i and c are just variables. Variable assignment has no side effects.

Upvotes: 4

Related Questions