协变数据类型:为什么 return 类型必须与其 'parent method' return 类型相同或其子类型?
Covariant data types: Why return type must be same as or child of its 'parent method' return type?
由于这个概念不是很出名,我就稍微介绍一下吧。
Covariant return type of a method is one that can be replaced by a
"narrower" type when the method is overridden in a subclass.
所以我可以很好地编译这个小程序(因为 String 是 Object 的子对象):
public class House {
Object someMethod(){
return null;
}
}
class DogHouse extends House{
@Override
String someMethod() {
return null;
}
}
这个规则很容易记住,但我不明白。我的问题是:
为什么 DogHouse 中 someMethod 中的 return 类型只能是 return 的相同对象或子对象在 class House 中输入 someMethod?我希望问题很清楚。
或者..(例如)如果我在 class 中输入 return 类型 someMethod 为什么这段代码无法编译=]House Integer
例如? (字符串不是整数的子项)
发生了什么事'behind the scenes'所以我能理解吗?
理解这一点的方法是将子class 视为父class 的特定类型。这意味着它仍然需要遵守父级定义的行为。父 class 定义了 someMethod
方法 returns 和 Object
。 Subclasses 无法打破这种行为,但他们可以进一步指定它 - DogHouse
的 someMethod
仍然 returns 和 Object
,它只是发生了成为 String
.
由于这个概念不是很出名,我就稍微介绍一下吧。
Covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass.
所以我可以很好地编译这个小程序(因为 String 是 Object 的子对象):
public class House {
Object someMethod(){
return null;
}
}
class DogHouse extends House{
@Override
String someMethod() {
return null;
}
}
这个规则很容易记住,但我不明白。我的问题是:
为什么 DogHouse 中 someMethod 中的 return 类型只能是 return 的相同对象或子对象在 class House 中输入 someMethod?我希望问题很清楚。
或者..(例如)如果我在 class 中输入 return 类型 someMethod 为什么这段代码无法编译=]House Integer
例如? (字符串不是整数的子项)
发生了什么事'behind the scenes'所以我能理解吗?
理解这一点的方法是将子class 视为父class 的特定类型。这意味着它仍然需要遵守父级定义的行为。父 class 定义了 someMethod
方法 returns 和 Object
。 Subclasses 无法打破这种行为,但他们可以进一步指定它 - DogHouse
的 someMethod
仍然 returns 和 Object
,它只是发生了成为 String
.