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?