关于java问题?

来源:百度知道 编辑:UC知道 时间:2024/06/22 01:49:56
class A
{
private static int count=0;
public A()
{
count++;
}
public void finalize()
{
count--;
}
public static void main(String [] args)
{
new A();
new A();
new A();
Runtime.getRuntime().gc();
A rt=new A();
System.out.println("count="+count);
}
}
结果为什么是count=4?
class Person
{
public void finalize()
{
System.out.println("the object is going");
}
public static void main(String [] args)
{
new Person();
new Person();
new Person();
Runtime.getRuntime().gc();
System.out.println("the program is ending!");

}
}
the result is :
the program is ending!
the object is going
the objec

当然是4了,方法A构造了四次,全局变量4次被累加.
你用的finalize()方法是垃圾回收机制,当系统执行完System.out.println("the program is ending!"); 程序将要结束时,系统才会执行finalize()方法中的语句来释放掉这三个实例所占用的内在空间,所以会产生如上的结果.

http://hi.baidu.com/ta22/blog/item/92f08444ad501483b2b7dcf6.html 你可以看看这个
你只要掌握住一点就行,finalize()这个方法是在java 回收对象,变量前执行的,所以当这个程序要结束时也就是快要回收对象时,这个方法才会被执行. 书上写得也不一定都对的.