I just wanted to create a shallow and a deep copy of an object. I know that in the deep copy you create a new object with the values of the object you want to copy to prevent a side effect. The thing I noticed I can't get a side effect on my shallow copy, but I don't understand why.
public class Joo {
public String name;
public Joo(String a) {
this.name = a;
}
public Joo(Joo a) {
this.name = a.name;
}
public static void main(String[] args) {
Joo a = new Joo("Bernt");
Joo b = new Joo(a);
System.out.println("a :" +a.name); //a :Bernt
System.out.println("b :" +b.name); //b :Bernt
b.name = "Ernie";
System.out.println("a :" +a.name); //a :Bernt
System.out.println("b :" +b.name); //b :Ernie
}
}
I was expected that when I change b.name its also changes a.name because b.name is just the reference of the a.name object and not a real copy.