简体   繁体   English

为什么分配的Java变量的行为类似于参考?

[英]why is assigned java variable behaving like a reference?

Hi i dont know if this question has already been asked before but this is getting really annoying... 嗨,我不知道是否已经有人问过这个问题,但这真是令人讨厌...

Ok so i have a class called Test: 好的,所以我有一个叫做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;
    }
}

And of course my main class... 当然是我的主要班级...

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?
    }
}

if there is something im doing wrong please let me know, thank you very much!! 如果我做错了什么,请让我知道,非常感谢!

In your program you have a SINGLE instance of Test , you just name it differently every time. 在您的程序中,您有一个Test的SINGLE实例,您每次都只是用不同的名称命名。

Test anotherNumber = Test.testObject;

Does NOT create a new object. 创建新对象。 It only reference to the same object, you say "Whenever I write anotherNumber , I actually meant to write Test.testObject ". 它仅引用相同的对象,您说“每当我编写anotherNumber ,我实际上就是在编写Test.testObject ”。

So, when you later change anotherNumber.number = 50; 因此,当您以后更改anotherNumber.number = 50; , you do: Test.testObject.number = 50; ,您可以这样做: Test.testObject.number = 50; , and thus when you print Test.testObject , you see 50. ,因此在打印Test.testObject时看到50。


Edit: 编辑:

If you want to be able to create copy of some object, you can introduce a copy constructor: 如果您希望能够创建某个对象的副本,则可以引入一个副本构造函数:

public Test(Test original) { 
   this.number = original.number;
}

And use it with someOtherNumber = new Test(Test.testObject); 并与someOtherNumber = new Test(Test.testObject);

When in your class Test, you are creating a new Object of Test that is always 5. So take out the Test object that you created in the Test class, then use the following code in your main method: 在Test类中,您将创建一个始终为5的Test对象。因此,请取出在Test类中创建的Test对象,然后在main方法中使用以下代码:

Test anotherNumber = new Test(5);
System.out.println(anotherNumber.number);
anotherNumber.number = 50;
System.out.println(anotherNumber.number);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM