Type Conversion and Casting
Upcasting and Downcasting
In an inheritance hierarchy, one object can be reached through variables of several types. A Dog object fits in a Dog variable, an Animal variable or an Object variable. Changing the type of the reference you use to reach it is reference casting. You need it whenever you keep mixed subclass objects in one array or list, pass them to a method that takes a superclass parameter, or want a subclass-only method back. The examples use Java.
Static type and dynamic type
A reference expression's static type is its compile-time type. For a variable, this comes from its declaration. For a non-null reference value, the dynamic type is the class of the referenced object, fixed when that object was created. A null reference points to no object and therefore has no referenced object's dynamic class.
Animal a = new Dog(); // static type Animal, dynamic type DogThe compiler uses the static type to determine which members are available, so a.bark() does not compile even though the object can bark. A reference cast never changes the object; it changes only the type through which you view it.
Upcasting
Upcasting converts a reference to a superclass type, moving up the hierarchy. Every Dog is an Animal, so the conversion can never fail and Java performs it implicitly:
Dog d = new Dog();
Animal a = d; // implicit upcast
Animal b = (Animal) d; // legal, but the cast is redundantAfter the upcast, a == d is true: both variables hold a reference to the same object. Through a you can reach the accessible members declared in or inherited by Animal, although an overridden instance method still runs the Dog version because the object has not changed.
Downcasting
Downcasting converts a superclass reference to a subclass type. Not every Animal is a Dog, so you must write the cast, and the JVM verifies it when the line runs.
Animal a = new Dog();
Dog d = (Dog) a; // compiles and succeeds: the object is a Dog
d.bark();
Animal c = new Cat();
Dog e = (Dog) c; // compiles, then fails at run timeA cast between two classes passes two checks. At compile time, one class must be a subclass of the other, so that the object could possibly be of the target type; casting a Dog variable to Cat is rejected as inconvertible types. For a cast permitted at compile time, the run-time rule is:
A legal cast of null succeeds and yields null. When a non-null reference fails the rule, the JVM throws a ClassCastException. Member access binds more tightly than a cast, so (Dog) a.bark() tries to cast the result of a.bark(); write ((Dog) a).bark() instead.
Conversion | Direction | Cast written? | Checked | Can it fail? |
|---|---|---|---|---|
Dog to Animal | Upcast | No, implicit | Compile time | No |
Animal to Dog | Downcast | Yes, (Dog) | Compile time and run time | Yes, if the reference is non-null and the object is not a Dog or subclass |
Dog to Cat | Between sibling classes | Not allowed | Compile time | Always rejected |
What to remember
- The static type controls which members are available at compile time; a non-null object's dynamic type determines whether a downcast succeeds and which overridden instance method runs.
- Upcasting is implicit and always succeeds.
- Downcasting needs an explicit cast and throws ClassCastException when a non-null reference points to an object outside the target class and its subclasses.
- A legal cast of null succeeds and yields null.
- A cast between two unrelated classes does not compile.
- A cast changes the type of the reference expression, never the object.
Example: Casting through a vehicle hierarchy
A fleet-management program uses these classes:
class Vehicle { int wheels() { return 4; } }
class Car extends Vehicle { int seats() { return 5; } }
class ElectricCar extends Car { int rangeKm() { return 420; } }
class Truck extends Vehicle { int wheels() { return 6; } }Part of the main method reads:
Vehicle v = new ElectricCar(); // line 1
Car c = (Car) v; // line 2
ElectricCar e = (ElectricCar) c; // line 3
Truck t = (Truck) v; // line 4
Truck u = (Truck) c; // line 5a) Which of lines 1 to 5 compile?
The compiler looks only at static types and asks whether the source class and the target class are related by inheritance.
- Line 1 assigns an ElectricCar to a Vehicle variable. That is an implicit upcast, so it compiles.
- Line 2 casts from static type ________ down to its subclass Car, so it compiles.
- Line 3 casts from static type Car down to its subclass ElectricCar, so it compiles.
- Line 4 casts from Vehicle down to its subclass Truck. The compiler cannot rule out a Truck object in v, so it compiles.
- Line 5 casts from static type Car to Truck. Neither class is a subclass of the other; they are siblings under Vehicle, so no Car reference can ever point to a Truck.
Lines 1 to 4 compile, and line 5 is a compile-time error (inconvertible types).
b) Line 5 is deleted. What happens when lines 1 to 4 run?
At run time the JVM compares the dynamic type of the object with the target type of each cast. Only one object exists, created on line 1, and its dynamic type is ________.
- Line 2: an ElectricCar is a Car, so the cast succeeds and c refers to the same object as v.
- Line 3: the object is exactly an ElectricCar, so the cast succeeds.
- Line 4: an ElectricCar is neither a Truck nor a subclass of Truck, so the check fails.
Lines 2 and 3 succeed, and line 4 throws a ClassCastException. Line 4 compiled only because the cast was possible for some Vehicle; that says nothing about this particular object.
c) In a separate run, with lines 1 to 5 above omitted, the program runs this loop. What does it print?
Vehicle[] fleet = { new Car(), new Truck(), new ElectricCar(), new Truck(), new ElectricCar() };
int total = 0;
for (Vehicle x : fleet) {
if (x instanceof ElectricCar ec) total += ec.rangeKm();
else if (x instanceof Car car) total += car.seats();
else total += x.wheels();
}
System.out.println(total);Each element is upcast to Vehicle when it is stored in the array, and the loop downcasts it again with pattern-matching instanceof. Trace the branches in the order they are written.
- The Car fails the ElectricCar test but passes the Car test, so it adds seats(), which is ________.
- Each Truck fails both tests and reaches the last branch. wheels() runs the Truck version because the object is still a Truck, so each adds ________.
- Each ElectricCar passes the first test and adds rangeKm(), which is ________.
The program prints 857. The order of the tests matters: an ElectricCar is also a Car, so if the Car test came first, both electric cars would add 5 instead and the total would be 27.
A Java document service returns null when no document is available. The following statements execute in order inside a method, using these class declarations:
class Document {}
class Report extends Document {
int pageCount() {
return 12;
}
}Document missing = null;
Report report = (Report) missing;
boolean supported = missing instanceof Report;
int pages = report.pageCount();Complete the statements using Java literals and the exact exception class name without its package prefix.
Immediately after the cast, report contains . The value assigned to supported is . The final statement throws .
In a Java payroll program, class Manager extends class Employee and adds a method approveBudget() that Employee does not declare. A variable is declared as Employee e = new Manager();. Which statement compiles and calls approveBudget() on the object that e refers to?