用子类参数覆盖子类方法? [英] Overriding subclass methods with subclassed arguments?
问题描述
当子类覆盖时,如何强制基本方法接受相同的特定子类实例?
How can I force base methods to take in the same specific subclass instance when overriden by a subclass?
ie:
abstract class Animal {
def mateWith(that: Animal)
}
class Cow extends Animal {
override def mateWith...?
}
逻辑上,牛
应该只能 mateWith
另一个 Cow
。但是,如果我执行覆盖def mateWith(that:Cow)
,这实际上并没有覆盖基类方法(我想要它,因为我想强制执行它存在于子类中。
Logically, a Cow
should only be able to mateWith
another Cow
. However, if I do override def mateWith(that: Cow)
, this doesn't actually override the base class method (which I want it to, since I want to enforce its existence in the subclass).
我可以检查以确保其他实例是Cow类型,如果不是则抛出异常 - 这是我最好的选择?如果我有更多动物怎么办?我将不得不重复抛出异常代码。
I could check to make sure the other instance is of type Cow, and throw an exception if it isn't - is this my best option? What if I have more animals? I would have to repeat the exception-throwing code.
推荐答案
abstract class Animal[T <: Animal[T]] {
def mateWith(that: T)
}
class Cow extends Animal[Cow] {
override def mateWith(that: Cow) { println("cow") }
}
class Dog extends Animal[Dog] {
override def mateWith(that: Dog) { println("dog") }
}
并像这样使用:
scala> (new Cow).mateWith(new Cow)
cow
scala> (new Cow).mateWith(new Dog)
<console>:17: error: type mismatch;
found : Dog
required: Cow
(new Cow).mateWith(new Dog)
^
不需要抛出异常代码;类型系统在编译时为你处理它!
No exception-throwing code needed; the type system handles it for you at compile-time!
这篇关于用子类参数覆盖子类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!