在Java中,按照标准的代码风格和设计原则,什么时候修改对象的内部数据比较合适,什么时候用修改后的数据新建一个对象比较合适呢?
例如,假设我有一个类 Vector2D,它包含一个 x 分量和一个 y 分量,我想旋转该向量:
public class Vector2D{
private int x;
private int y;
public Vector2D(int x, int y){
this.x = x;
this.y = y;
}
public void rotate(double angle){
//code for finding rotated vector
x = rotated_x;
y = rotated_y;
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以旋转 Vector2D 对象 vector1.rotate(angle)
public class Vector2D{
private final int x;
private final int y;
public Vector2D(int x, int y){
this.x = x;
this.y = y;
}
public Vector2D rotate(double angle){
//code …Run Code Online (Sandbox Code Playgroud)