重写方法时返回类型 [英] returning type when we overriding methods

查看:268
本文介绍了重写方法时返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.
我正在读凯瑟琳·塞拉(Katherine Sierra)和贝特·贝茨(Bert Bates)的书,这是我读过的声明,但我听不懂:

Hello .
I am reading a book by Katherine Sierra and Bert Bates the is a statement i read but i didn''t understood it :

In a method with an object reference return type, you can return any
object type that can be implicitly cast to the declared return type.


谁能向我解释这个说法.


can anyone explain to me this statement.

推荐答案



将一种类型转换为另一种类型.
我想像一下我们有这些元素:
-从A继承的B类.
-函数F1返回一个A类类型的对象.


在F1内,您可以处理类型B的对象,并希望将其作为函数返回值返回.
为此,您需要将B强制转换为A(称为UP-CASTING),然后可以将其返回.


Hi,

A cast a conversion from a type to another.
Iimagine we have these elements :
- Class B that inherits from A.
- Functions F1 return a A class type object.


Inside F1 you handle ojects of type B and you want to return it as function return value.
To do that you need to cast B to A ( it is called UP-CASTING) then you can return it.


B objectB = new B()
...
retObject = (A) objectB;
return retObject;




希望对您有帮助




Hope this helps


这篇关于重写方法时返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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