Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the finalize() method in java.lang.Object "protected"?

Tags:

java

finalize

Out of curiosity,

Why is the finalize() method's access modifier is made as protected. Why cant it be public? Can someone explain me any specific reason behind this?

Also, I came to know that finalize() method is called only once. If I call it twice in my program internally, what is happening? Will the garbage collector call this again?

private void dummyCall() {     try {         finalize();         finalize();     } catch (Throwable e) {         e.printStackTrace();//NOT REACHES EXCEPTION     } } 
like image 296
bragboy Avatar asked Feb 18 '10 19:02

bragboy


2 Answers

I answer your question with another question:

Why finalize method shouldn't be protected?

In general, you should try to keep things as much private as possible. That's what encapsulation is all about. Otherwise, you could make everything public. finalize can't be private (since derived classes should be able to access it to be able to override it), so it should at least be protected but why give out more access when it's not desirable?


After reading your comment more carefully, I guess I see your main point now. I think your point is since everything derives from java.lang.Object and consequently accesses its protected members, it wouldn't make any difference for it (or any method in java.lang.Object for that matter) to be public as opposed to protected. Personally, I'd count this as a design flaw in Java. This is indeed fixed in C#. The problem is not why finalize is protected. That's OK. The real issue is that you shouldn't be able to call protected methods in the base class through an object reference of the base class type. Eric Lippert has a blog entry discussing why allowing such kind of access to protected members is a bad idea which is further elaborated on Stack Overflow in this question.

like image 193
mmx Avatar answered Sep 20 '22 14:09

mmx


Why is the finalize() method's access modifier is made as protected. Why cant it be public?

It is not public because it shouldn't be invoked by anyone other than the JVM. However, it must be protected so that it can be overridden by subclasses who need to define behavior for it.

If i call it twice in my program, internally what is happening?

You can call it all you want, its just a method after all. However, much like public static void main(String [] args), it has special meaning to the JVM

Will the garbage collector call this again?

Yes

like image 41
Kevin Avatar answered Sep 17 '22 14:09

Kevin