Próbuję pojąć stringi no i wiem, że można je stworzyć na dwa podstawowe sposoby
String s1 = "test";
String s2 = "test";
Są to referencję do stringów o wartości test w puli stringów w stercie, więc robiąc s2 = "zmiana" nic w s1 się nie zmieni. Zmieni się tylko referencja s2.
Natomiast tworząc stringi w taki sposób:
String s1 = new String("test");
String s2 = s1;
I teraz robiąc s2 = "zmiana" zmieni się tylko też s2, a myślałem, że tutaj zmieni się wartość tego stringa w s1 a tak się nie dzieje. Dlaczego?
Spróbowałem to na własnej klasie:
public class Customer {
private String name;
private int age;
+konstruktor, settery i gettery
}
I później:
Customer mainCustomer = new Customer("Adam", 16);
Customer anotherCustomer = mainCustomer;
System.out.println("MainCustomer: " + mainCustomer.getName() + " " + mainCustomer.getAge());
anotherCustomer.setName("Już nie Adam");
System.out.println("MainCustomer: " + mainCustomer.getName() + " " + mainCustomer.getAge());
System.out.println("anotherCustomer: " + anotherCustomer.getName() + " " + anotherCustomer.getAge());
Wynik będzie:
MainCustomer: Adam 16
MainCustomer: Już nie Adam 16
anotherCustomer: Już nie Adam 16
Czym różni się tutaj obiekt Stringa i Customer, że działają inaczej. I czy jest sytuacja, że robiąc s2 = s1 i s2 = "zmiana", zmiana zajdzie też w s1?