Search code examples
javainheritancegarbage-collectionjvisualvm

If not parent object, what does GC clear up on the parent after super.finalize() method?


My question is based on the fact that:

  • Whenever we create a sub class, the superclass object is not created even if the super class constructor is invoked.
  • If finalize() method is defined in subclass then super.finalize() must be called also.

That's all well and good. But When I use the jvisualjvm (under the /bin directory of the JDK installation - I do not see any super class object instance created and that is as I expect. Superclass object is not created when we create its subclass instance.

My question: What does GC clear up on part of the super class?

If you double click and open the jvisualjvm, you can see (if you halt your program with a Thread.sleep(forEnoughTimeToCheck_jvisualjvm) )...you will not find the super class instance there, only the subclass...probably just the reference. So does the GC clears up the super class reference whenever it does?

I have seen many many blogs and posts on SO but I haven't seen any of them explain what GC clears up on part of super class.


Solution

  • So does the GC clears up the super class reference whenever it does?

    There's no such thing as a reference to a superclass instance. With two classes like

    class Super {
        int a;
    }
    
    class Sub extends Super {
        int b;
    }
    

    and new Sub() you get an object containing fields a and b. All these superclass stuff is interesting only in some places, like accessing sub.a or instanceof checks.

    Whenever we create a sub class, the superclass object is not created even if the super class constructor is invoked.

    Yes.... a call like new Sub() does three things:

    • it allocates space for an object big enough to hold two ints
    • it initializes a part of it by calling the code of Super#Super
    • it initializes a part of it by calling the code of Sub#Super

    The call to super() as contained or implied in the Sub constructor body does no allocation at all, just the initialization.


    The GC doesn't care at all. All it needs is to know where are references to other objects (nowhere in my example as there are just primitive fields).

    If finalize() method is defined in subclass then super.finalize() must be called also.

    finalize is a special method which gets special handling, but again, if Sub#finalize overrides Super#finalize, then the latter becomes irrelevant (unless explicitly called from the former, which it should be, but that's another story).

    Note that finalize gets used very rarely, maybe for one object in million. You shouldn't override it, unless you know that you really need it. It's not what the GC is based on.