我开始研究 Java 中的 OOP 概念,我试图为点、线、平面和曲面创建一个基本类,但我在使用我创建的方法时遇到了问题。
public class Punto{
public double x, y;
public Punto(double pX, double pY){
this.x = pX;
this.y = pY;
}
public String puntoTela(){
return "( " + x + " , " + y + " )";
}
public void rotacion(double grado) {
double rad = (grado * Math.PI) / 180;
this.x = (this.x * Math.cos(rad) + this.y * - Math.sin(rad));
this.y = (this.x * Math.sin(rad) + this.y * Math.cos(rad));
}
}
我的问题是:如果我声明 Punto p = new Punto(5, 2)
并调用 rotation
方法,我将无法返回到原始值。
public class Ejemplo {
public static void main(String[] args){
Punto p = new Punto(5, 2);
System.out.println(p.puntoTela()); // shows (5, 2)
p.rotacion(45);
System.out.println(p.puntoTela()); // shows (5, 2) after rotatin 90 deg = (2.1, 2.9)
System.out.println(p.x); // 2.1 i want original value of 5
}
}
我尝试为旋转方法创建局部变量,但它不起作用我该怎么办??谢谢!
最佳答案
您可以创建 Punto
类 immutable . rotation
方法(以及其他“mutator”方法)将返回一个新的(修改后的)对象,而不是更改原始对象:
public Punto rotacion(double grado) {
double rad = (grado * Math.PI) / 180;
double newX = (this.x * Math.cos(rad) + this.y * - Math.sin(rad));
double newY = (this.x * Math.sin(rad) + this.y * Math.cos(rad));
return new Punto(newX, newY);
}
您可以在许多 JDK 类中观察到这种模式,例如 BigDecimal
、LocalDate
、String
等。
那么用法是:
public static void main(String[] args) {
Punto p = new Punto(5, 2);
System.out.println(p.puntoTela()); // shows (5, 2)
// Note that the new value is assigned to a new variable,
// so that we still have access to the old value
Punto rotated = p.rotacion(45);
System.out.println(rotated.puntoTela()); // rotated
System.out.println(p.x); // original
}
关于java - 在修改对象的方法调用后获取原始对象状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52414254/