【发布时间】:2011-11-25 12:19:25
【问题描述】:
我正在重写子类中的受保护函数。
假设我有两个课程,Apple 和 Fruit。 我已经准备好所有变量,这只是一个简化版本。
class FruitBasket
protected function getRandom():Fruit
{
// return random piece of fruit
}
class AppleBasket extends FruitBasket
protected override function getRandom():Apple
{
// return random apple
}
class Fruit
class Apple extends Fruit
例子很简单。问题是 getRandom 函数的类型取决于它自己的类型。一个返回一个苹果,另一个返回一个水果。 当然,我会收到有关覆盖和强制的错误。
我尝试返回 Fruit 而不是 Apple,但该对象不是苹果,因此它没有 Apple 特定的属性。 问题在于鸭子打字。我无法更改第三个类,它对每个对象执行 getRandom() 函数,我需要 Apples 稍有不同。
如何覆盖 Apple 中的 getRandom 函数,使其返回苹果而不是水果?
【问题讨论】: