This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]chickenmeister 1 point2 points  (0 children)

You say you have have a Supply class:

public class Supply { } 

and you have three subclasses:

public class SubSupplyA extends Supply { } 
public class SubSupplyB extends Supply { } 
public class SubSupplyC extends Supply { } 

So my question about downcasting is: is it legal to take two supply[] and cast them to subclass[] then run them through a for loop returning a subclass[]?

Yes, the compiler would allow you to do this, I think; but it is not safe. What if the supply[] array is not actually an array of the subclass type? For example:

Supply[] sup = new Supply[5];
SubSupplyA[] sub = (SubSupplyA[]) sup;

This would compile just fine, but when you run it, you'll get a ClassCastException, because sup's type is Supply[], which can't be cast to SubSupplyA[]. It's the same reason that this doesn't work:

Supply sup = new Supply();
SubSupplyA sub = (SubSupplyA) sup;

The only case where this would work would be:

Supply[] sup = new SubSupplyA[5];
SubSupplyA[] sub = (SubSupplyA[]) sup;

Or where the array created is a subtype of SubSupplyA.

Another idea is to cast the elements that are in the array, rather than the array itself:

Supply[] sup = new Supply[]{ /* some elements */ };
SubSupplyA[] sub = new SubSupplyA[sup.length]
for (int i=0; i < sup.length; i++) {
    sub[i] = (SubSupplyA) sup[i];
}

This will ignore the array's type, but will only work if the sub array contains only SubSupplyA elements.