上图就是 两个对象使用一个方法的内存图:接下来是代码
public class Demo02PhoneTwo {
public static void main(String[] args) {
Phone one = new Phone();
System.out.println(one.brand);//null
System.out.println(one.price);//0.0
System.out.println(one.color);//null
System.out.println("============");
one.brand = "苹果";
one.color = "黑色";
one.price = 6888.0;
System.out.println(one.brand);//苹果
System.out.println(one.price);//6888.0
System.out.println(one.color);//黑色
System.out.println("============");
one.call("乔布斯");
one.sendMessage();
System.out.println("============");
Phone two = new Phone();
System.out.println(two.brand);//null
System.out.println(two.price);//0.0
System.out.println(two.color);//null
System.out.println("============");
two.brand = "三星";
two.color = "蓝色";
two.price = 5999.0;
System.out.println(two.brand);//三星
System.out.println(two.price);//5999.0
System.out.println(two.color);//蓝色
System.out.println("============");
two.call("偶吧");//给偶吧打电话
two.sendMessage();//群发短信
}
}
两个引用指向同意对象的内存图:
先代码 后上图
主要是换了一行代码:Phone two =one 而不再是nwe了
public class Demo03PhoneSame {
public static void main(String[] args) {
Phone one = new Phone();
System.out.println(one.brand);//null
System.out.println(one.price);//0.0
System.out.println(one.color);//null
System.out.println("============");
one.brand = "苹果";
one.color = "黑色";
one.price = 6888.0;
System.out.println(one.brand);//苹果
System.out.println(one.price);//6888.0
System.out.println(one.color);//黑色
System.out.println("============");
one.call("乔布斯");
one.sendMessage();
System.out.println("============");
//将one当中的保存的对象地址值赋值给two
Phone two = one;
System.out.println(two.brand);//苹果
System.out.println(two.price);//8388.0
System.out.println(two.color);//黑色
System.out.println("============");
two.brand = "三星";
two.color = "蓝色";
two.price = 5999.0;
System.out.println(two.brand);//三星
System.out.println(two.price);//5999.0
System.out.println(two.color);//蓝色
System.out.println("============");
two.call("偶吧");//给偶吧打电话
two.sendMessage();//群发短信
}
}
关键就在Phone two = one; 这一行代码,就是把one的地址交给类two ,虽然两个名称不一样,但是两个名称保存的地址是相同的,这个叫着两个对象的名称指向了同一个对象,对象的名称也叫着对象的引用名。两个对象引用指向了同一个对象空间
接下来是图: