Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Mục đích của việc ghi đè phương thức finalize() trong Java?

Phương thức finalize() là phương thức định nghĩa sẵn trong lớp Object và là protected. Mục đích của finalize() có thể ghi đè để đưa vào mã dọn dẹp (cleanup code) hoặc giải phóng tài nguyên hệ thống trước khi đối tượng bị garbage collected. Nếu ghi đè finalize(), trách nhiệm của chúng ta là gọi tường minh finalize(). finalize() chỉ được gọi một lần bởi JVM hoặc đối tượng cho trước.

Cú pháp

protected void finalize() throws Throwable

Ví dụ

public class FinalizeMethodTest { 
    protected void finalize() throws Throwable { 
        try { 
            System.out.println("Calling finalize() method of FinalizeMethodTest class"); 
        } catch(Throwable th) { 
            throw th; 
        } finally { 
            System.out.println("Calling finalize() method of Object class"); 
             super.finalize(); 
        } 
    } 
    
    public static void main(String[] args) throws Throwable { 
        FinalizeMethodTest test = new FinalizeMethodTest(); 
        String str = "finalize() method in Java"; 
        str = null; 
        System.out.println(str); 
        test.finalize(); 
    } 
}

Kết quả

null Calling finalize() method of FinalizeMethodTest class Calling finalize() method of Object class