一个变量a引用一个被实例化的对象Human1,另一个变量b初始化时将a的值赋给b,即b = a;含义为b的引用对象为a的引用对象(Human1),a和b都指向Human1,此时Human的实例化对象总个数只有一个。而不是复制一个Human1 ,然后b再指向该复制。
ps:此处引用和指向一个意思。
package com.structure;
public class Human {
private String sex;
private int age;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void display(){
System.out.println("sex:" + sex + ",age" + age);
}
public static void main(String[] args){
Human hm = new Human();
hm.setAge(16);
hm.setSex("male");
hm.display();
Human hm2 = hm;
hm2.display();
System.out.println("----------------------");
System.out.println("the boy grows up");
hm.setAge(17);
hm.display();
hm2.display();
System.out.println("----------------------");
System.out.println("the boy becomes a girl");
Human hm3 = new Human();
hm3.setAge(17);
hm3.setSex("female");
hm = hm3;
hm.display();
hm2.display();
hm3.display();
System.out.println("----------------------");
int a = 6;
int b = a;
System.out.println("a = " + a + ",b = " + b);
System.out.println("----------------------");
a = 7;
System.out.println("a = " + a + ",b = " + b);
System.out.println("----------------------");
}
}
根据万物皆对象的思想上述理解同样适用于基础类型