Java:对象引用和重新分配

时间:2018-06-27 07:07:53

标签: java

对于不耐烦的人,来自Core Java:

  

变量只能保存对对象的引用...

然后我像这样尝试一下,它似乎可以工作:

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*/

但是,它似乎并不仅仅适用于String对象或原始类型(不过,可以承认,后者并不是类实例的对象):

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*/

我想知道为什么这种二分法?谢谢

ps:Person类的属性是公共的,以避免此简单示例的变体,访问器

1 个答案:

答案 0 :(得分:0)

您没有重新分配“ a”

a.m_name = "Bob";

尝试这样做

a = new Person("Bob", 20);

然后,您将获得与列出的字符串示例相似的行为。