0

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?

3
  • 5
    What would you do in race(...) with a robot which is not a racer?
    – Radiodef
    May 27, 2017 at 15:19
  • 2
    public static void race(Robot arg) { ((Racer) arg).sprint(); }. It will crash and burn with ClassCastException if you pass a Robot that is not a Racer, so why would you want to forego the compiler type-checking that prevents that from happening?
    – Andreas
    May 27, 2017 at 15:24
  • If the method is written to take 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 a Robot is not necessarily a Racer, and b) should either be protected against ClassCastException 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.
    – Lew Bloch
    May 27, 2017 at 15:28

1 Answer 1

0

Method argument can not typecast. you can give super class as an argument, so that inside method u can typecast based on run-time object.

2
  • What would be the syntax for that? May 27, 2017 at 19:17
  • you can create Robot class as an Interface and give an abstract method. Create a class which implements Robot class and then override abstract method. public interface Robot{ public void sprint(); } public class Racer implements Robot{ public void sprint(){ System.out.println("abc"); } } public class Test { public static void race(Robot arg) { arg.sprint(); } } May 28, 2017 at 5:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.