Pages

Add Points

interface CartesianCoord
{
    public double getX();
    public double getY();
    public CartesianCoord plus(CartesianCoord other);
}

interface EuclideanCoord extends CartesianCoord
{
    public double getZ();
    public EuclideanCoord plus(EuclideanCoord other);
}

class Point2D
implements CartesianCoord
{
    private final double x;
    private final double y;
    public Point2D(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public double getX() { return x; }
    public double getY() { return y; }
    public CartesianCoord plus(CartesianCoord other)
    {
        return new Point2D(this.x + other.getX(), this.y + other.getY());
    }
    public String toString()
    {
        return "(" + x + "," + y + ")";
    }
}

class Point3D extends Point2D
implements EuclideanCoord
{
    private final double z;
    public Point3D(double x, double y, double z)
    {
        super(x, y);
        this.z = z;
    }
    public double getZ() { return z; }
    public EuclideanCoord plus(EuclideanCoord other)
    {
        return new Point3D(getX() + other.getX(),
            getY() + other.getY(),
            this.z + other.getZ());
    }
    public String toString()
    {
        return "(" + getX() + "," + getY() + "," + z + ")";
    }
}

public class AddPoints
{
    public static void main(String[] args)
    {
        CartesianCoord p1 = new Point2D(Math.PI, Math.E);
        EuclideanCoord p2 = new Point3D(-5.1, 3.0, 1);
        EuclideanCoord p3 = new Point3D(-5.1, 3.0, 1);
        System.out.println(p1.plus(p2));
        System.out.println(p2.plus(p3));
    }
}