我理解类是引用类型,例如我创建了以下类:
class Class {
String s = "Hello";
public void change() {
s = "Bye";
} }
通过以下代码,我了解到Class
是一个引用类型:
Class c1 = new Class();
Class c2 = c1; //now has the same reference as c1
System.out.println(c1.s); //prints Hello
System.out.println(c2.s); //prints Hello
c2.change(); //changes s to Bye
System.out.println(c1.s); //prints Bye
System.out.println(c2.s); //prints Bye
现在我想用一个字符串做同样的事情,但不起作用。这里我做错了什么?
String s1 = "Hello";
String s2 = s1; //now has the same reference as s1 right?
System.out.println(s1); //prints Hello
System.out.println(s2); //prints Hello
s2 = "Bye"; //now changes s2 (so s1 as well because of the same reference?) to Bye
System.out.println(s1); //prints Hello (why isn't it changed to Bye?)
System.out.println(s2); //prints Bye
s2 = "Bye"
操作。 - JB Nizets1
和s2
是两个引用,都指向相同的字符串“Hello”。一旦更改s2
,也就是让s2
指向一个新的字符串“Bye”,而s1
仍然指向原来的字符串“Hello”。 - zhhClass
,因为 JDK 已经有一个(相当常用的)同名类。这会让人感到困惑;如果我看到一个叫做Class
的类,我的默认假设是它是 JDK 中的那个。 - yshavit