I've created a class called Test
that has a constructor and one instance variable String name
:
class Test {
String name;
Test(String name){
this.name = name;
}
}
I instantiate it like this:
Test first = new Test("First");
Test second = first;
first.name = "Change First";
System.out.println("First: " + first.name);
System.out.println("Second: " + second.name);
... and predictably get this:
First: Change First
Second: Change First
This makes sense to me. I'm assigning the second Object to the same memory location referenced in the first - when I change the first, the second changes and vice versa.
Take this:
String x = new String("Hello");
String y = x;
x = new String("Change");
System.out.println("x: " + x);
System.out.println("y: " + y);
The above gives the output:
x: Change
y: Hello
Why is this? They're both extend the Object
class, so why do they behave so differently? Do any other Object
derivatives behave like this?