我正在尝试定义一个使用相应伴随对象的特征,即使用该特征的类的组合对象。
例如,我有:
:paste
class Parent {
def callMyCompanion = print(Parent.salute)
}
object Parent {
def salute = "Hello from Parent companion object"
}
class Child extends Parent {
}
object Child {
def salute = "Hello from Child companion object"
}
然后我创建一个父对象:
scala> val p = new Parent()
p: Parent = Parent@1ecf669
scala> p.callMyCompanion
Hello from Parent companion object
但是带着孩子:
scala> val c = new Child()
c: Child = Child@4fd986
scala> c.callMyCompanion
Hello from Parent companion object
我想得到:来自 Child 伴侣对象的 Hello
我怎样才能实现它???
-- 编辑澄清
感谢您的回复,但在这种情况下, callMyCompanion 是我创建的一个虚拟方法,只是为了解释自己,我试图重用父方法,而不必在每个实现它的类中重写它......
到目前为止我找到的解决方案是实现一个使用伴随对象的实例方法......