Java:从超类变量调用子类方法 [英] Java: Calling a subclass method from superclass variable

查看:162
本文介绍了Java:从超类变量调用子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(问题先前在此处提出.答案.

(Question previously asked here. I did not quite get the desired answer.)

书中的引文:

如果您要调用对象的子类定义的方法,该怎么办 被超类的变量引用?假设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();

在上面的代码片段中,它显示了一个新的 Softball 对象,该对象正在创建并分配为对变量 b 的引用,该变量自类以来是完全合法的>垒球类的子类.但是引号指出(间接地),在使用变量调用 Softball 类中的方法之前,必须将变量强制转换为 Softball 类型.这是为什么?为什么我不能直接使用 Ball 类型的变量b(包含对垒球对象的引用)来调用所需的方法?变量 b 已具有对象.

In the code snippet above, it shows a new Softball object being created and assigned as a reference to the variable b, which is completely legal since the class Softball is a subclass of the class Ball. Yet the quote states (indirectly) that you have to cast the variable to type Softball before you can use the variable to call methods from the Softball class. Why is that? Why can't I directly use the variable b of type Ball (which contains the reference to the Softball object) to call the desired method? The variable b already has the object.

(注意:我已经阅读

(Note: I already read this post.)

推荐答案

Java是一种静态类型的语言.

Java is a statically typed language.

这意味着编译器将检查变量的类型是否具有您尝试调用的方法.

That means that the compiler checks if the type of the variable has the method you are trying to call.

变量b的类型为Ball. Ball没有riseBall方法.

The type of your variable b is Ball. Ball does not have a riseBall method.

这意味着您的代码将崩溃,除非在运行时b恰好包含一个Softball(编译器无法保证).您可能知道它确实如此,但是您也必须说服编译器(即为变量提供必要的类型).

That means your code would crash unless that b at runtime happens to contain a Softball (which the compiler cannot guarantee). You may know that it does, but you have to convince the compiler, too (i.e. give your variables the necessary types).

这篇关于Java:从超类变量调用子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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