Downcasting
Casting down the inheritance tree is known as downcasting.
- Downcasting requires the cast operator
().
Person p = new Employee();
Employee e = (Employee) p; // this works
The compiler lets us cast to any class in the hierarchy.
* If the object in memory isn't actually what we cast its reference to according to the is-a relationship, our program will break at runtime with a ClassCastException.
Person p = new Person(); // Person in memory
Employee e = (Employee) p; // Compiles, but fails at runtime
// with ClassCastException
instanceof Operator¶
We can use the instanceof operator to check if the object in memory could be cast to another type.
* If the test returns true, we can safely cast to that type.
Person p = new Employee();
if (p instanceof Employee) {
Employee e = (Employee) p;
e.getTitle();
}
Practice Exercise¶
instanceofcan only use operands that are a reference type ornull. A primitive likeint xresults in a compiler error.Reference: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.20.2
Drill¶
(If you did not finish
VehicleApp, use the version provided in the...solutions.vehiclespackage)
Polymorphism/com.example.polymorphism.labs.vehicles.VehicleApp* ChangecalculateVehicleRegistrationto use arateof0.04if the vehicle is-aAutomobileorTruck, and0.065if the vehicle is-aBoat. Otherwise use0.02.(Solution: VehicleApp2.java)