Overloading a method in an immutable class

走远了吗. 提交于 2019-12-13 04:39:08

问题


Say that I have an immutable Point class with x and y parameters, and an add method defined like this:

class Point:
  Point add(int x, int y):
    return new Point(this.x + x, this.y + y);

Since it's immutable, it returns a new Point. This is all well and good until we have a class that extends Point and redefines add.

class ColoredPoint extends Point:
  ColoredPoint add(int x, int y):
    return new ColoredPoint(this.x + x, this.y + y, this.width, this.height)

We have to write the new definition because otherwise the add method on ColoredPoint would return Point which is bad. But now this won't work in most languages because we're overriding add but we're only disambiguating on return type. Languages don't allow you to have methods that are only disambiguated on return type, because that can be ambiguous in most cases.

So what do we do?

The only solutions I see are:

  • Make them both implement some interface like IPositionable
  • Give up on immutability.

Anything else?


回答1:


If you want to enforce immutability, you cannot have subclasses. See for example java.lang.String, which is a final class for this reason: To prevent people from subclassing String to make it mutable.

Also, why would Rect extend Point in the first place? Isn't it a completely different thing? Geometry-wise, they don't even exist in the same dimension.

Finally, I cannot see the connection between the problem of methods on subclasses returning a more restrained type (and some languages not supporting this well), and immutability.



来源:https://stackoverflow.com/questions/11183187/overloading-a-method-in-an-immutable-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!