1

Possible Duplicate:
Why is the finalize() method in java.lang.Object “protected”?

The finalize method is defined with a protected scope, then how is it possible that some other object such as the garbage collector is able to call it.

1
  • 1
    while the GC doesn't use this mechanism (it plays by it's own rules), just because a method is private, doesn't mean that you can't execute it even from outside the class, see AccessibleObject.setAccessible(boolean); This applies to accessings fields as well. Access modifiers are to control sane use of a class. Mar 3, 2011 at 4:32

4 Answers 4

7

Because the garbage collector is part of the language specification and thus can do whatever the language specification says it can.

2

protected is not the same as private, and the garbage collector could access it even if it were private.

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

1

That's JVM magic. Just like private methods invocation during serialization

1

From the perspective of the Java Language Specification, the garbage collector is not an object, and is not governed by the normal access rules. It is "part of the JVM" and can do things that ordinary Java code can't do. (Indeed, it is probably not implemented as Java code at all!)

Think about it. If the GC was required to conform to the access rules, then it would not be able to access private fields of objects during the mark phase, and therefore could not determine whether objects were reachable. In other words, it wouldn't be able to fulfil the JLS requirements for memory management.

Not the answer you're looking for? Browse other questions tagged or ask your own question.