如何将js重写为java,(instanceofusage,replaceoverload)



假设我们在js 中有这样的函数

this.add = function (x, y) {
if (x instanceof Vector2d) {
this.x += x.x;   
this.y += x.y;
return this;
}
this.x += x;
this.y += y;
return this;
};

我必须在java中重载它吗?就像:

public Vector2D add(Vector2D other) {
this.x += other.x;
this.y += other.y;
return new Vector2D(this.x, this.y);
}
public Vector2D add(double number) {
this.x += number;
this.y += number;
return new Vector2D(this.x, this.y);
}

或者有什么更好/更聪明/更紧凑的方法来做这些事情吗?

public class Vector2D {
private double x;
private double y;
//...
public Vector2D add(Vector2D other) {
this.x += other.x;
this.y += other.y;
return this;
}
public Vector2D add(double x, double y) {
this.x += x;
this.y += y;
return this;
}
//...
}

您可以在每次调用方法时返回this,而不是像在js版本中那样创建新的Vector2D对象。

但我觉得这类问题更适合代码审查社区:https://codereview.stackexchange.com

最新更新