scala:重用子类实现作为两个不同类的子类?
为了简化我的实际代码,假设有两个类,一个是另一个的子类:
class Chair {
val canFold = false;
// ...
}
class FoldableChair extends Chair {
val canFold = true;
// ...
}
在我的实现中,我可能有数百个 Chair 或 FoldableChair 的其他子类:
class Armchair extends ... {}
class DeckChair extends ... {}
//... etc
对于这些子类中的每一个,假设每个子类都有一个很长的实现,但是我希望能够让它有时扩展 Chair,有时扩展 FoldableChair - 而不重复代码。我想这样做而不扩展子类本身。这有可能吗?我需要使用特征来做到这一点吗?
我还希望能够创建子类的特定实例,有时扩展 Chair,有时扩展 FoldableChair,但这种选择是在实例化它时做出的。这也可能吗?谢谢!
编辑:澄清一下,我真正想要的是:
class Armchair extends Chair {}
class ArmchairFoldable extends FoldableChair {}
但是 Armchair 和 ArmchairFoldable 的实现完全相同。也就是说,我不想重复他们的实现。
To simplify my actual code let's say there are two classes, one a subclass of the other:
class Chair {
val canFold = false;
// ...
}
class FoldableChair extends Chair {
val canFold = true;
// ...
}
and in my implementation I will have potentially hundreds of other subclasses of Chair or FoldableChair:
class Armchair extends ... {}
class DeckChair extends ... {}
//... etc
For each of these subclasses, suppose each one has a lengthy implementation but I want to be able to have it sometimes extend Chair and sometimes extend FoldableChair - without duplicating the code. I'd like to do so without having the subclass itself be extended. Is this possible somehow? Do I need to use traits to do this?
I'd also like to be able to create particular instances of a subclass which sometimes extend Chair and sometimes extend FoldableChair, but that choice is made when instantiating it. Is this possible too? Thanks!
Edit: to clarify, what I really want is this:
class Armchair extends Chair {}
class ArmchairFoldable extends FoldableChair {}
but the implementation of Armchair and ArmchairFoldable are exactly the same. That is, I'd like to not duplicate their implementations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用实现特征;即,与类混合并为其他成员提供实现的特征。
示例:
那么你可以这样写:
You can use an implementation trait; i.e., a trait that you mix in with a class and that provides additional members with their implementation.
Example:
Then you can write: