In my opinion, neither nor: Both are n-tuples with different n. The problem with this is that most languages don't allow types to be parameterized by a value.
When deciding a certain inheritance, you should consider matrix multiplication.
/1 0\ /2\ ? /1 0 0\ /2\
\0 1/ · |3| = |0 1 0| · \3/
\4/ \0 0 0/
You are implicitly arguing that one or both multiplications work (and should possibly be equivalent). At this point every mathematician is having a heart attack, because you violated certain rules about the required dimensionality.
I think it is obvious that Vector3
can't be a subtype of Vector2
, and not the other way round: You cannot generally use one in place of the other. But both have common properties. I would probably define an interface Vector
with methods like component(i)
which gives the i-th component (instead of getX
, getY
, …), size()
which gives the dimensionality, and norm()
which calculates the length.
If you are hell-bent on having one type inheriting from another, consider these test cases:
// failure with Vector3 <: Vector2 -- vec.z can be != 0
if (vec instanceof Vector2)
assert vec.z == 0;
// failure with Vector3 <: Vector2 -- vec.z can be != 0
if (vec instanceof Vector2)
assert vec.norm() == sqrt(vec.x^2 + vec.y^2); // euclidean norm - invalid in non-cartesian systems
// failure with Vector2 <: Vector3 if they are mutable (Circle-Ellipse Problem)
if (vec instanceof Vector2) {
vec.z = 42;
assert vec.z == 0;
}
// failures concerning dimensionality with *any* inheritance relation
// when considering matrix multiplication
This means that I have to grudgingly admit that having Vector2 inherit from Vector3 would work in most cases, if they are immutable and you aren't doing anything more fancy than addition or scalar multiplication.
Note On Coordinates
If you don't want to do vector algebra but just want to represent coordinates, then this answer would be different, because 2D coordinates can be viewed as a projection of 3D coordinates into a plane (or any other surface parameterizable by two numbers). In this case, every 2D coordinate would also have a 3D coordinate, but the two coordinates are from two different coordinate systems. Projection into the z = 0
-plane is one very special case of this where it is possible to view the 2D-coordinate as a kind of 3D-coordinate. This is not generally the case in all 2D coordinate systems.