【发布时间】:2021-10-31 07:13:08
【问题描述】:
考虑下面的代码:
class Student{
int id;
String name;
}
public class Main
{
public static void main(String[] args) {
Student s1 = new Student();
s1.id = 10;
s1.name = "student 1";
Student s2 = new Student();
s2.id = 20;
s2.name = "student 2";
Student s3 = s1;
s3.name = "student 3";
System.out.println(s1.id +" "+s1.name);
System.out.println(s3.id +" "+s3.name);
}
}
对于上面的代码,输出是:
10 student 3
10 student 3
但是当我使用整数对象、字符串对象或其他一些包装类对象时,输出是不同的。考虑下面的代码:
public class Main
{
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
Integer c = a;
c = 30;
System.out.println(a);
System.out.println(c);
}
}
上述代码的输出是:
10
30
在我的自定义对象中,如果我更改一个对象的值,那么两个对象的值都会更改,但为什么在 Integer 和 String 等对象中却不是这样。
我的困惑是引用如何在 Integer、String、Double 等类中工作。
【问题讨论】: