Search code examples
javaoverridingfinalize

Why is subclass's finalize method, which overrides java.lang.Object's finalize method, called?


Here is the code block

public class Person {

    int age;
    String name;

    //
    @Override
    public void finalize() throws Throwable{
        System.out.println("Garbage collected --->" + this);
    }
}

class test{

    public static void main(String[] args)  {
        Person p = new Person();
        System.out.println(p.getClass());

        p = null;
        System.gc();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

System.gc() called finalize() method, but the Object's finalize() should be called, why are the subclass's and the superclass's both called? Thx for your answer!

I guess when superclass's method and subclass's homonymous method are both called, and the instance is of subclass, the priority of subclass's method is higher than superclass's?


Solution

  • Apart from the fact the finalization has been deprecated, how do you infer the superclass' finalize is called? You are true that subclass method overrides superclass method and it actually happens in your case - only subclass' finalize is invoked. To invoke superclass' finalize you should invoke super.finalize() but it wouldn't have any effect anyway since default java.lang.Object implementation is empty.