英文:
Covariant data types: Why return type must be same as or child of its 'parent method' return type?
问题
作为一个中文翻译,以下是您提供的内容的翻译:
由于这不是一个非常著名的概念,我将进行简要介绍。
> 协变返回类型是指在子类中重写方法时,可以将其替换为“更窄”的类型。
因此,我可以编译这个小程序(因为String是Object的子类):
public class House {
Object someMethod(){
return null;
}
}
class DogHouse extends House{
@Override
String someMethod() {
return null;
}
}
这个规则足够简单,但我不明白它。我的问题是:
为什么在DogHouse的someMethod中,返回类型只能与House类中的someMethod的返回类型相同或是其子类?我希望问题相当清楚。
又或者...(例如)如果我在House类中的someMethod中放入了返回类型Integer
,为什么这段代码无法编译?(String不是Integer的子类)
背后到底发生了什么,以便我能够理解呢?
英文:
As this is not so famous concept, I will make a little intro.
> Covariant return type of a method is one that can be replaced by a
> "narrower" type when the method is overridden in a subclass.
So I can compile just fine this little program (as String is child of Object):
public class House {
Object someMethod(){
return null;
}
}
class DogHouse extends House{
@Override
String someMethod() {
return null;
}
}
The rule is easy enough to remember, but I don't understand it. My question is this:
Why can the return type in someMethod in DogHouse only be the same or child of return type in someMethod in class House? I hope the question is quite clear.
Or..(for example) why this code wouldn't compile if I had put return type in someMethod in class House Integer
for example? (String is not a child of Integer)
What is happening 'behind the scenes' so I can understand it?
答案1
得分: 2
理解这一点的方法是将子类看作父类的特定类型。这意味着它仍然需要遵循父类定义的行为。父类定义了一个返回“Object”的“someMethod”方法。子类不能打破这个行为,但它们可以进一步指定它 - “DogHouse”的“someMethod”仍然返回一个“Object”,只是碰巧是一个“String”。
英文:
The way to understand this is to think of the subclass as a specific type of the parent class. This means it still needs to adhere to the behavior defined by the parent. The parent class defines a someMethod
method that returns an Object
. Subclasses can't break this behavior, but they can further specify it - a DogHouse
's someMethod
still returns an Object
, it just happens to be a String
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论