嗨,我不知道此问题是否已经被问过,但这真的很烦人......
好的,我有一个名为Test的课程:
public class Test {
public static Test testObject = new Test(5);//Creates a test object with an initialized value of 5;
int number;
public Test(int number){
this.number = number;
}
}
当然是我的主要班级......
public class Main {
public static void main(String args[]){
Test anotherObject = Test.testObject;//this is not a reference right?
System.out.println(Test.testObject.number);//This prints 5
anotherObject.number = 50;// changing anotherObject's number. NOT testObject's Number.
System.out.println(Test.testObject.number);//if that was true this whould of still been 5, but it prints 50!!?? why does testObject's number even change if im not even changing that value?
}
}
如果有什么事情我做错了请告诉我,非常感谢!!
答案 0 :(得分:1)
在您的程序中,您有一个Test
的SINGLE实例,每次都只是以不同的名称命名。
Test anotherNumber = Test.testObject;
不是否会创建新对象。它只引用同一个对象,你说"每当我写anotherNumber
时,我实际上是想写Test.testObject
"。
因此,当您稍后更改anotherNumber.number = 50;
时,您执行:Test.testObject.number = 50;
,因此当您打印Test.testObject
时,您会看到50。
编辑:
如果您希望能够创建某个对象的副本,可以引入一个复制构造函数:
public Test(Test original) {
this.number = original.number;
}
并将其与someOtherNumber = new Test(Test.testObject);
答案 1 :(得分:0)
在Test类中,您正在创建一个始终为5的新测试对象。因此,取出您在Test类中创建的Test对象,然后在main方法中使用以下代码:
Test anotherNumber = new Test(5);
System.out.println(anotherNumber.number);
anotherNumber.number = 50;
System.out.println(anotherNumber.number);