重载不可变类中的方法 [英] Overloading a method in an immutable class

查看:73
本文介绍了重载不可变类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个带有xy参数的不可变Point类,以及这样定义的add方法:

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);

因为它是不可变的,所以它返回一个新的Point.直到我们有了一个扩展Point并重新定义add的类,这一切都很好.

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)

我们必须编写新的定义,因为否则,ColoredPoint上的add方法将返回Point,这很糟糕.但是现在这不适用于大多数语言,因为我们覆盖了add,但是我们只是对返回类型进行了歧义.语言不允许您只对返回类型进行歧义的方法,因为在大多数情况下,这可能是模棱两可的.

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.

那我们该怎么办?

我看到的唯一解决方案是:

The only solutions I see are:

  • 使它们都实现某些接口,例如IPositionable
  • 放弃不变性.

还有什么?

推荐答案

如果要强制执行不变性,则不能有子类.例如,参见java.lang.String,它是final类,其原因如下:为了防止人们将String子类化以使其可变.

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.

此外,为什么Rect首先扩展Point?这不是完全不同的事情吗?从几何角度看,它们甚至不存在于同一维中.

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.

这篇关于重载不可变类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆