为什么 finalize 在下面的代码中没有给出空指针异常



为什么当对象设为 null 时,下面的代码在 finalize 方法中没有给出空指针异常?

class Person{  
public int a;
public void finalize(){
    //System.out.println("finalize called"+this.hashCode());
    System.out.println("finalize called"+this.a);
}  
public static void main(String[] args){  
    Person f1=new Person();  
    f1.a=10;
    Person f2=new Person();  
    f1=null;  
    f2=null;  
    System.gc();  
}}

O/P : 最终调用0finalize called10<</p>

div class="one_answers">

对象不能设为 null,只能设为引用。

仅仅因为您将f1f2设置为 null,并不意味着finalize()会抛出NPE。它正在访问永远不能为空的this引用。

f1 --> Object <-- (implicit this accessible from inside the instance)
f2 --> Object <-- (--""--)
f1 = null; f2 = null;
       Object <-- (implicit this) previously f1 referred to this Object
       Object <-- (implicit this) previously f2 referred to this Object

对象永远不会为空,这是无稽之谈。引用可以设为空,并且可以销毁对象(因此(。

f1f2不是对象,而是对对象的引用。当你写f1=null时,这只意味着这个引用不再指向任何对象,并且以前指向的对象少了一个引用。垃圾回收(粗略地(跟踪您对引用所做的所有操作,当对象不再被引用时,它们首先被放入垃圾箱,然后在需要时回收或销毁,但即使在该阶段,对象也存在。当回收/销毁时,机器将在回收/销毁之前调用finalize,然后在调用对象时存在finalize对象(如果不是,如何在对象上调用finalize

class Person{  
public int a;
public void finalize(){
    //System.out.println("finalize called"+this.hashCode());
    System.out.println("finalize called"+this.a);
}  
public static void main(String[] args){  
    Person f1=new Person();  
    f1.a=10;
    Person f2=new Person();  
    f1=null;  
    f2=null;  
    System.out.println("f1 =" + f1 + " f2 = " + f2);
    System.gc(); 
    System.out.println("Below gc");
    System.out.println();
    System.out.println(f1.a);// **here O/P - NPE**
}}

输出 ->

f1 =空 f2 = 空

低于 gc

最终调用0 完成调用10

线程"main"中的异常 java.lang.NullPointerException at 基本。Person.main(Person.java:19(

最新更新