0

Now I Know this is a silly question,but still,finalize method is defined as protected in object class and and it would be inherited privately in our class.

and we know that finalize method run just before the object being destroyed,so my question is,if we do not override it?would it still run as it is there in a private form??

user3380123
  • 703
  • 1
  • 6
  • 14
  • Why don't you just try it? – Angelo Fuchs Apr 25 '14 at 07:53
  • @AngeloNeuschitzer and how would I do that?? – user3380123 Apr 25 '14 at 07:55
  • You write a class that inherits finalize as private and see what happens. Or if you want to know when the finalize method in Object gets called you start a debugger and place a watcher on it. – Angelo Fuchs Apr 25 '14 at 07:58
  • See [Why do finalizers have a “severe performance penalty”?](http://stackoverflow.com/questions/2860121/why-do-finalizers-have-a-severe-performance-penalty); trivial finalizers (i.e., not overridden from `Object`) won't be run. – Joe Apr 25 '14 at 08:08

3 Answers3

1

finalize method is defined as protected in object class and it would be inherited privately in our class.

No, It's not inherited as private into sub class.

Will finalize method run without overriding it?

Yes, It will run, since it's inherited.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • it is inherited as private,as we know that protected member of class are privately inherited in different package subclasses – user3380123 Apr 25 '14 at 07:57
  • @user3380123 No. Its not. Have a read of the access modifiers and how they can be altered. In short: you can make them wider (protected -> public) but never narrower (protected -> private) – Angelo Fuchs Apr 25 '14 at 08:07
1

You can't override finalize as private.

If you try you will get this error:

Cannot reduce the visibility of the inherited method from Object.

I think you should try to learn more about the access modifiers. protected doesn't ever (and can't) become private.

This works:

protected void finalize() throws Throwable {
    // something
}

This works as well:

public void finalize() throws Throwable {
    // something
}

This won't work:

private void finalize() throws Throwable {
    // something
}

Have a read of this answer: In Java, what's the difference between public, default, protected, and private?

Community
  • 1
  • 1
Angelo Fuchs
  • 9,825
  • 1
  • 35
  • 72
0

Yes, the finalize() method will still run even if you don't override it with your own implementation.

Keppil
  • 45,603
  • 8
  • 97
  • 119