Question

I tried the following code in a main method of a class that I wrote:

public static void main(String[] args){
    ...
    Object s = new Object();
    s.finalize();
    ...
}

However, the eclipse give me a tip that

The method finalize() from the type Object is not visible

I am so confused because the type Object has a protected finalized method, which is supposed to be visible by its own? Am I wrong anyway?

Was it helpful?

Solution

Object#finalize() is a protected method. You can't call it like that. A protected member of a class is inherited by it's direct subclass. You can access it inside that direct subclass on this reference, but not using the reference of that class directly.

It would be like this:

class Demo {
    public void test() { 
        this.finalize();
    } 
}

BTW, why do you want to invoke it? That method is automatically invoked by JVM to clear any resources that an object is using, just before the object is completely removed from the memory.

OTHER TIPS

finalize() method is called when an object is about to be destroyed.

If you have a custom class, then you can override this method in order to do something.
You shouldn't call this method directly. JVM's garbage collector will do that for you automatically.
And you shouldn't depend on the finalize() method to clear any resources, as it may never happen during the execution of your program.

protected means that you can only access that method if you are in the same package than the Object. And the Object is in package: java.lang.Object your program is in package com.yourpackage.something ==> you cannot access it from your package

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top