如何创建一个不可变的子类,其父类具有final的setter方法?

huangapple go评论104阅读模式
英文:

How can i make an immutable subclass of a superclass with final setter methods?

问题

我想创建一个不可变的Scala类,但我还想通过final setters扩展一个Java超类。\n\n这种情况是否可能?如果不行,有什么最佳方法(与扩展最相似)可以解决?

英文:

I would like to create an immutable scala class, but I also want to extend a java superclass with final setters.

Is this possible and if not, what would be the best (most similar to extending) work-around?

答案1

得分: 3

由于您无法覆盖final方法,这意味着即使您找到了一些技巧来扩展它(例如,使用另一种方法签名或委托调用),您仍然会在您的不可变类中拥有一个"public final"的setter方法,客户端可以使用它。我认为这是一个很大的缺陷,因为在所有情况下都无法保持不变性。

我建议定义一个新的类,不要从可变类继承,而是将某些操作委托给它,只委托那些不会创建可变性的操作。

通常在Java或像Guava这样的库中就是这样实现的,我们创建一个可变对象的私有内部字段,只公开不会改变列表本身的公共方法。

英文:

Since you can't override a final method, it means that even if you found some tricks to extends it (by for example, using another method signature or delegating the call), you still will have a "public final" setter method which can be used by your clients, in your Immutable class. Which is I think a big flaw since your Immutability won't be preserved in all cases.

I would suggest to define a new Class which does not extends from the Mutable one but delegates some operation to it, only the ones that does not create mutability.

It's often like this it's implemented in Java or in libraries like Guava, we create a private inner field of the mutable object, and we expose only publicly methods that won't alter the list itself.

huangapple
  • 本文由 发表于 2020年10月14日 17:11:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64350081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定