Search code examples
javaconstructorcloneable

Java - Implement Cloneable or add a constructor?


Hey I'm actually working with a custom Vector class on Java,

public class Vector {

    private double X;
    private double Y;

    public Vector(double x, double y) {
        this.X = x;
        this.Y = y;
    }

    public void setX(double x) {
        this.X = x;
    }
    public double getX(double x) {
        return this.X;
    }

    public void setY(double y) {
        this.Y = y;
    }
    public double getY(double y) {
        return this.Y;
    }

}

I wanted to add the multiply() method that would return this vector * by the specified factor like that,

public void multiply(double factor) {
    this.X *= factor;
    this.Y *= factor;
}

The thing is, when I use a function requiring a vector, I'd like to use it like

doSomething(ancientVector.multiply(-1D));

but the jvm isn't satisfied because the arg I send to the function is a void...

How could I also do to make it clean, should I implement Cloneable or create another constructor working the way multiply does?

doSomething(ancientVector.multiply(-1D));

OR add

public Vector(Vector previous, double mFactor) {
    this.X *= previous.getX() * mFactor;
    this.Y *= previous.getY() * mFactor;
}

Solution

  • I would keep the class immutable and return a new Vector:

    public Vector multiply(double factor) {
        return new Vector(X * factor, Y * factor);
    }