简体   繁体   中英

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:

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 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 ".

So, when you later change anotherNumber.number = 50; , you do: Test.testObject.number = 50; , and thus when you print Test.testObject , you see 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);

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 anotherNumber = new Test(5);
System.out.println(anotherNumber.number);
anotherNumber.number = 50;
System.out.println(anotherNumber.number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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