1

From a book:

What if you want to call a method that’s defined by a subclass from an object that’s referenced by a variable of the superclass? Suppose that the SoftBall class has a method named riseBall that isn’t defined by the Ball class. How can you call it from a Ball variable? One way to do that is to create a variable of the sub-class and then use an assignment statement to cast the object:"

Ball b = new SoftBall();
SoftBall s = (SoftBall)b;
// cast the Ball to a SoftBall
s.riseBall();

I don't understand this. Why can't I just directly call the method from the variable b? (The variable b in this case holds a Softball object). Why the casting?

1 Answers1

5

How can you call it from a Ball variable?

You can't. The compiler doesn't know that this Ball is a SoftBall as opposed to a BaseBall.

You have to cast explicitly. This is merely a way of saying to the compiler: "I know more about the type of this instance than you". The compiler trusts you (mostly: it wouldn't let you cast it to, say, a String), and lets you deal with the consequences (e.g. a potential ClassCastException)

Andy Turner
  • 137,514
  • 11
  • 162
  • 243