I want to know why finalize method in Object class is protected .and whats the comparision between public and protected in this issue.Because even though if they made protected any class can use this method because every class is a sub class of object.
If you are in beginners' then I should tell you to forget all about finalize(). Don't use it.
If you are more advanced, then finalize() is supposed to be called by the JVM, not from any of your classes at all, so it ought not to be public. If it had private or default access, then it would be impossible to override, so it must have protected access.
Joined: Apr 06, 2009
not from any of your classes at all, so it thought not to be public
hello sir... Even though it is protected all class can overide the method because every class is a sub class of Object class .Then what sort of difference will exists between Protected and public in this issue. protected in the sence only sub class can view public in the sence all classes can view .here even though my class is not extending the object class compiler by default extend the object class.
Actually, the behavior of "protected" is more subtle than you realize. Imagine three classes P, C1, and C2 (parent, child 1, and child 2.) P defines a protected method m(). Code in C1 can, of course, call m() on instances of P and on instances of C1 itself. But code in C1 can not call m() on instances of C2!
In terms of Object and finalize(), this means that code in any class C can call finalize() on its own instances, and super.finalize(), but that's it -- it can't call finalize on instances of any other class.
This is perfectly in line with the intended purpose of finalize(). Only the system is supposed to call it, but you need to be able to call super.finalize() if you override it. You should never try to call it on any other class.