【27】java中正确的清除

首先说明,java的垃圾回收机制只能回收内存里的数据,如果程序运行过程中向非内存的某些地方写入了数据,那末程序结束时我们需要将他们删除。

比如,一个画图程序,运行过程中,它向屏幕上“写”了一些数据(这些数据不是存储在内存中),那么我们需要多写一些代码将他们删除:

public class Shape {

public Shape(int i){
System.out.println("Shape constructor");
}

public void cleanup(){
System.out.println("Shape cleanup");
}
}
public class Circle extends Shape {

public Circle(int i){
super(i);
System.out.println("Circle constructor");
}

public void cleanup(){
System.out.println("Circle cleanup");
super.cleanup();
}
}
public class Triangle extends Shape {
public Triangle(int i){
super(i);
System.out.println("Triangle constructor");
}

public void cleanup(){
System.out.println("Triangle cleanup");
super.cleanup();
}
}
public class Line extends Shape {

private int start,end;

public Line(int start,int end){
super(start);

this.start = start;
this.end = end;

System.out.println("Drawing a line from " + start + " to " + end);
}

public void cleanup(){
System.out.println("Earsing the line from " + start + " to " + end);
super.cleanup();
}
}
public class CADSystem extends Shape {

private Circle circle;
private Triangle triangle;

private Line[] lines = new Line[10];//句柄数组,未绑定对象
/**
*
@param i
*/
public CADSystem(int i) {
super(i + 1);//一次初始化父类,组合类,自己
circle = new Circle(1);
triangle = new Triangle(1);

for(int j = 0;j <10;++j){//一次为数组里的每个句柄绑定对象
lines[j] = new Line(j, j*j);
}

System.out.println("CADSystem constructor");
}

public void cleanup(){//以与初始化相反的顺序进行删除
System.out.println("CADSystem cleanup");

for(int i = 0;i <10;++i){
lines[i].cleanup();
}

circle.cleanup();
triangle.cleanup();

super.cleanup();
}

/**
*
@param args
*/
public static void main(String[] args) {

CADSystem xCadSystem = new CADSystem(36);

try {

}finally{//finally,最终肯定要被执行的
xCadSystem.cleanup();
}
}
}






posted @ 2012-03-21 14:32  Marstar  阅读(300)  评论(0编辑  收藏  举报