程序示例:
class Car {
//private 是私有化的意思,private 修饰的属性只能在本类中访问。
private String color;
private int name;
public void setColor(String color){
this.color = color;
}
public String getColor(){
return color;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
//通过Public的对外公开的set方法来设置私有的属性值。
public void run(){
System.out.println("run....."+this.color); //this表示当前对象的上下文作用于。表现形式如Car@
}
public void introduce(){
System.out.println("我是一辆"+this.color+"车牌是"+this.carNo+this.name+"的豪车");
}
}
class TestCar {
//创建一个Car
Car car = new Car();
car.color = ‘绿色';
car.carNo = 'G3939';
car.name = '宝马'
}
第一步:在运行java类时也就是TestCar时,把TestCar.class加载到jvm中,然后把Main函数放入到方法区中。最后开始执行main方法,也就是压栈进入栈内存。
第二步:加载Car.class进入jvm,于是Car类中的方法最先加载进方法区(注意:成员变量暂时还没加载进栈内存中),也就是把run方法和introduce方法加载到方法区,在堆中开辟一个空间创建了一个Car对象,在栈中产生一个变量car指向堆中的对象,然后给car对象三个属性值。
第三步:car的run方法进栈,把car变量所指向的this赋值,执行方法体。
第四步:run方法出栈,run中的this消失。//符合先进后出
第五步:car变量消失,main出栈后消失。
第六步:由于car堆中的对象失去了变量的引用,变成了匿名对象,所以也被垃圾回收器回收了。
浙公网安备 33010602011771号