A 3D vector has 3 coordinates along the X, Y and Z-axis and is commonly used to represent geometry in computer graphics. In it simple form here it supports only one operation add
that computes the component-wise sum of two vectors.
Implementations like below can often be found in the wild:
public class Vec3 {
private double x, y, z;
public Vec3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vec3 add(Vec3 v) {
x += v.x;
y += v.y;
z += v.z;
return this;
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ")";
}
}
System.out.println(new Vec3(1.0, 2.0 ,3.0));
This implementation has a fluent interface for it's add
method that allows easy chaining of operations on a vector. For example the addition of 3 vectors can be written as
Vec3 sumABC = a.add(b).add(c);
Now, consider the follwing declarations of vector variables a
and b
:
Vec3 a = new Vec3(0, 1, 0);
Vec3 b = new Vec3(1, 0, 0);
System.out.println(a);
System.out.println(b);
Assume, the following calculations need to be performed:
$$ \begin{eqnarray} \vec{c} & = & \vec{a} + \vec{b} \\ \vec{d} & = & \vec{c} + \vec{a} \end{eqnarray} $$Try to predict, which values variables c
and d
will have after the following implementation of this calculation has been executed:
Vec3 a = new Vec3(0, 1, 0);
Vec3 b = new Vec3(1, 0, 0);
Vec3 c = a.add(b);
Vec3 d = c.add(a);
System.out.println(c);
System.out.println(d);