Java:自动转换如何工作? [英] Java: How does automatic casting work?

查看:58
本文介绍了Java:自动转换如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自一本书:

如果您要调用对象的子类定义的方法,该怎么办 被超类的变量引用?假设SoftBall类 具有一个Ball类未定义的名为riseBall的方法.你怎么 从Ball变量中调用它?一种方法是创建子类的变量,然后使用赋值语句强制转换对象:"

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();

我不明白这一点.为什么不能直接从变量 b 调用该方法? (在这种情况下,变量 b 包含一个 Softball 对象).为什么要投射?

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?

推荐答案

如何从Ball变量中调用它?

How can you call it from a Ball variable?

不能.编译器不知道此BallSoftBall而不是BaseBall.

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

您必须显式投射.这只是对编译器的一种说法:我比您更了解此实例的类型".编译器信任您(大多数情况:它不会让您将其转换为String),并让您处理后果(例如潜在的ClassCastException)

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)

这篇关于Java:自动转换如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆