Reputation: 3
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!!
Upvotes: 0
Views: 49
Reputation: 178411
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);
Upvotes: 1
Reputation: 513
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);
Upvotes: 0