Let's say I have a class called Robot. From the Robot class, I have a subclass called Racer. Two subclasses called Swimmer and Runner both extend Racer.
Racer (and all of its children) have a method called sprint().
In another class, I write a static class method called race that takes a Racer argument (or any of its children). In the race method, I utilize the sprint method, which is again, unique to Racer and its children.
The code runs successfully, but what if I wanted to pass a Robot argument through the sprint method? What is the code that would allow me to cast the Robot as a Racer?
I tried to do
public static void race((Racer) Robot arg) {
//race method here
}
but it did not work. Any ideas?
race(...)
with a robot which is not a racer?public static void race(Robot arg) { ((Racer) arg).sprint(); }
. It will crash and burn withClassCastException
if you pass aRobot
that is not aRacer
, so why would you want to forego the compiler type-checking that prevents that from happening?Racer
, then it must receive a reference to an instance of that type. Narrowing reference conversion ("downcasting") is something one should (almost) never do. Your cast a) might not work because aRobot
is not necessarily aRacer
, and b) should either be protected againstClassCastException
in case of "a)", or less desirably, catch and handle the exception. However, the best approach is not to downcast. Write the method to take the argument type that you actually in truth really in reality plan to pass to it.