From Core Java for the Impatient:
a variable can only hold a reference to an object ...
and I try it out like this and it seems to work:
public class Person{
public String m_name;
public int m_age;
Person (final String name, final int age){
m_name = name;
m_age = age;
}
public static void main(String[] args){
Person a = new Person("John", 45);
Person b = a;
System.out.printf("Person a is %s, aged %d\n", a.m_name, a.m_age);
System.out.printf("Person b is %s, aged %d\n", b.m_name, b.m_age);
a.m_name = "Bob";
System.out.printf("Person a is now %s, aged %d\n", a.m_name, a.m_age);
System.out.printf("Person b is now %s, aged %d\n", b.m_name, b.m_age);
}
}
/*Output:
Person a is John, aged 45
Person b is John, aged 45
Person a is now Bob, aged 45
Person b is now Bob, aged 45*/
However, it doesn't seem to work for just String objects or primitive types (though, admittedly latter are not objects in the sense of being class instances):
String aS = "John";
String bS = aS;
aS = "Bob";
System.out.println(aS + '\n' + bS);
/*Output:
Bob
John*/
int a = 10;
int b = a;
a = 5;
System.out.printf("a = %d, b = %d", a, b);
/*Output:
a = 5, b = 10*/
I'm wondering why this dichotomy? Thanks
ps: Person class attributes public to avoid mutators, accessors for this simple example