Course contentsShow
← Java
Lesson 448 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

Upcasting and Downcasting with Arrays

Exploring how upcasting and downcasting apply to array types and covariance.

Upcasting and Downcasting with Arrays

What you'll learn: How upcasting and downcasting work when applied to entire arrays, not just individual objects.

Arrays Have Types Too

Just like individual objects, arrays themselves have types. When you create a Dog[], that entire array has the type "array of Dog." This means arrays participate in the inheritance hierarchy just like their component types do.

Upcasting Arrays: Covariance

Java arrays are covariant, which means if Dog is a subtype of Animal, then Dog[] is considered a subtype of Animal[]. You can upcast an entire array reference:

Dog[] dogs = new Dog[3];
Animal[] animals = dogs;  // Implicit upcast - legal!

This looks convenient, but there's a catch: the underlying array is still physically a Dog[]. If you try to insert a Cat through the Animal[] reference, you'll get an ArrayStoreException at runtime:

animals[0] = new Cat();  // Compiles, but throws ArrayStoreException!

Downcasting Arrays

You can downcast array references using explicit cast syntax, just like with objects:

Animal[] animals = new Dog[3];
Dog[] dogs = (Dog[]) animals;  // Explicit downcast

Use instanceof to check safely before downcasting:

if (animals instanceof Dog[]) {
    Dog[] dogs = (Dog[]) animals;
}

The Covariance Problem

Array covariance can break type safety because the compiler allows assignments that fail at runtime. This is why generics (which you'll learn later) take a different, safer approach.

Key Takeaway: Arrays are covariant (Dog[] is-a Animal[]), allowing implicit upcasting of array references, but runtime checks prevent storing incompatible types, and downcasting arrays requires explicit casts and instanceof checks for safety.