Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection

 
Niranjan Prasad
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why finalize() is declared protected?
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check this

javaranch
 
Niranjan Prasad
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can u plse tell me in more detail y it is not public and y it is
protected.

I have read the explanation given,but i was still unclear.
Every method is invoked by the JVM on the relevant object.
Here also finalize() is invoked by JVM on relevant object.

Niranjan
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Niranjan

Did you study Edwin Dalorzo post it clearly tells why finalize method is protected


The finalize method is intended to be executed by the JVM just before GC collects garbage.

What is the minimum accessibility you could give to a method so that it could be overriden by any other sublass of object?

The answer is: protected.

You can override the method and do it public if you want, however, according to the contract of the finalize method, it would not make any sense.

A method is public if you pretend to offer some service through it, but no other class or object should invoke finalize directly. It should only be invoked by JVM before garbage collection.

Then, the best you can do is declare it protected.

Why?, well, If you do it private, it cannot be overriden, if you do it package accessible it cannot be overriden by classes in other packages. If you do it public, well, we already talked about it.

Then the best option is to make it protected.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic