public class Student {
int score;
int age;
String name;
Computer computer;
public void study() {
System.out.println("studying...");
}
}
public class Computer {
int price;
String brand;
}public class Test {
public static void main(String[] args) {
Student stu = new Student();
stu.name = "xiaoming";
stu.age = 10;
stu.study();
Computer c = new Computer();
c.brand = "Hasse";
System.out.println(c.brand);
stu.computer = c;
System.out.println(stu.computer.brand);
// System.out.println("----------------------------------------");
//
// c.brand = "Dell";
//
// System.out.println(c.brand);
// System.out.println(stu.computer.brand);
//
// System.out.println(stu.computer.brand == c.brand);
}
}
为进一步理解,我们把注释内容去掉:
⑨重新将Computer实例的brand属性指向"Dell"常量,那stu.computer.brand指向谁呢?Dell还是Hasse?
c.brand = "Dell";
根据刚才的分析可知:
stu通过地址引用Student实例,而该实例的computer的指向和c的指向是同一个Computer实例,因而改变该Computer实例的brand属性的指向,两者都会改变。
举个例子:
访问大明,和访问大明的儿子的爸爸,实质上访问的是同一个对象:大明。
因而,最终的结果是true。
理解字符串常量及常量池
下面我们添加新的代码,如下:
String str = "Dell";
System.out.println(c.brand == str);
结果会如何呢?
根据常量池具有共享性,可知并不会生成新的常量"Dell",而是会把str通过地址指向原来的"Dell",因而结果是true
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |