本文介绍了被覆盖的方法可以在返回类型上有所不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
重写方法可以不同的返回类型吗?
解决方案
Java支持重写方法的协变返回类型。这意味着重写的方法可能具有更多特定的返回类型。也就是说,只要新的返回类型可以分配给你要覆盖的方法的返回类型,就允许这样做。
例如:
class ShapeBuilder {
...
public Shape build(){
....
}
类CircleBuilder扩展ShapeBuilder {
...
@Override
public Circle build(){
....
}
这是在:
(| R2 |指的是R2的擦除,如。)
Can overridden methods have different return types?
解决方案
Java supports covariant return types for overridden methods. This means an overridden method may have a more specific return type. That is, as long as the new return type is assignable to the return type of the method you are overriding, it's allowed.
For example:
class ShapeBuilder {
...
public Shape build() {
....
}
class CircleBuilder extends ShapeBuilder{
...
@Override
public Circle build() {
....
}
This is specified in section 8.4.5 of the Java Language Specification:
("|R2|" refers to the erasure of R2, as defined in §4.6 of the JLS.)
这篇关于被覆盖的方法可以在返回类型上有所不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!