在java中覆盖具有不同返回类型的方法? [英] Overriding a method with different return types in java?

查看:119
本文介绍了在java中覆盖具有不同返回类型的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过一本书,它说我可以覆盖一个方法,如果它有相同的签名。根据书中方法的签名是Method_Name +传递的参数。

I have read a book and it says I can override a method if it has the same signature. according to the book the signature of a method is Method_Name + Parameters passed.

根据本书,我可以覆盖具有不同返回类型的方法。实际上是否可以在Java中覆盖具有不同返回类型的方法?因为我在网上做了一些搜索,我发现人们说要覆盖一个方法,返回类型也应该是相同的。

as per the book, i can override a method which has different return types. Is it actually possible to override a method with different return type in Java? because i have done a some search on the net i found people saying that to override a method the return type should be same as well.

根据书中它也说当我们尝试使用相同的方法名称和参数但不同的返回类型重载方法时,java将抛出编译错误,因为签名仅表示方法名称和参数。如果这是真的,我们应该能够覆盖具有不同返回类型的方法。

according to the book it also says the java will throw a compile error when we try to overload a method with same method name and parameters but different return types since the signature means only the method name and parameters. If this is true, we should be able to override a method with different return type.

请帮助我理解这一点。在此先感谢。

Please help me to understand this. Thanks in advance.

推荐答案

您可以返回不同的类型,只要它与被覆盖方法的返回类型兼容即可。兼容意味着:它是被重写方法返回的类或接口的子类,子接口或实现。

You can return a different type, as long as it's compatible with the return type of the overridden method. Compatible means: it's a subclass, sub-interface, or implementation of the class or interface returned by the overridden method.

这是合乎逻辑的。如果一个方法返回一个Animal,并且你的派生类返回一个Cow,那么你就不会破坏超类方法的契约,因为一个Cow就是一个Animal。如果派生类返回香蕉,那就不再正确,因为香蕉不是动物。

And that's logical. If a method returns an Animal, and your derived class returns a Cow, you're not breaking the contract of the superclass method, since a Cow is an Animal. If the derived class returns a Banana, that isn't correct anymore, since a Banana is not an Animal.

这篇关于在java中覆盖具有不同返回类型的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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