英文:
Instance of custom object being replaced when another is created java
问题
以下是翻译好的内容:
我有类似以下的代码,
public class ComplexSO {
public static double real;
public static double imaginary;
public ComplexSO(double cReal, double cImaginary) {
real = cReal;
imaginary = cImaginary;
}
public static ComplexSO selfSquare() {
return new ComplexSO(Math.pow(real, 2) - Math.pow(imaginary, 2),
2 * real * imaginary);
}
public static ComplexSO add(Complex other) {
return new ComplexSO(real + other.real, imaginary + other.imaginary);
}
public static void main(String[] args) {
ComplexSO c = new ComplexSO(1, 2);
System.out.println("c.real = " + c.real + ", c.imaginary = " + c.imaginary);
ComplexSO d = new ComplexSO(2, 3);
System.out.println("c.real = " + c.real + ", c.imaginary = " + c.imaginary);
}
}
当我运行这段代码时,我得到以下输出:
c.real = 1.0, c.imaginary = 2.0
c.real = 2.0, c.imaginary = 3.0
我不是对面向对象语言(C++ 和 Python)完全陌生,但对于 Java 我还比较新手,这段代码对我来说也毫无意义。请帮忙解释一下。
英文:
I have code like,
public class ComplexSO {
public static double real;
public static double imaginary;
public ComplexSO(double cReal, double cImaginary) {
real = cReal;
imaginary = cImaginary;
}
public static ComplexSO selfSquare() {
return new ComplexSO(Math.pow(real, 2) - Math.pow(imaginary, 2),
2 * real * imaginary);
}
public static ComplexSO add(Complex other) {
return new ComplexSO(real + other.real, imaginary + other.imaginary);
}
public static void main(String[] args) {
ComplexSO c = new ComplexSO(1, 2);
System.out.println("c.real = " + c.real + ", c.imaginary = " + c.imaginary);
ComplexSO d = new ComplexSO(2, 3);
System.out.println("c.real = " + c.real + ", c.imaginary = " + c.imaginary);
}
}
and when I run this I get the output:
c.real = 1.0, c.imaginary = 2.0
c.real = 2.0, c.imaginary = 3.0
I am not new to object oriented languages (C++ and python), but I am new to java, and this simply makes no sense to me. Please halp.
答案1
得分: 1
在Java中,类的静态属性是全局的。每个类定义只有一个值。同样地,静态方法在全局范围内操作,而不是在类实例上操作。只需从real、imaginary、selfSquare和add中移除static关键字,您就应该能看到正确的行为。您的main方法需要保持为静态。
英文:
In Java, static properties of a class are global. There is only one value per class definition. Similarly, static methods operate globally and not on class instances. Simply remove static from real, imaginary, selfSquare, and add and you should see the correct behavior. Your main method will need to remain static.
答案2
得分: 1
因为类的每个实例引用相同副本的静态变量。
所以这行代码 ComplexSO d = new ComplexSO(2, 3); 引用了静态变量double和imaginary,从而覆盖了先前的值1和2。
英文:
Because each instance of a class references the same copy of a static variable
So the line ComplexSO d = new ComplexSO(2, 3); references to the static variables double and imaginary and therefore overwrites the previous values 1 and 2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论