0

We have Constructors in Java which are analogous to Constructors in C++ which would create the object by automatically chaining(Consirering default non parameterized constructors) its constructors from base class to object being constructed.

Now we have finalizers in java which would be same as destructors in C++. And C++ chains its destructors from most derived class to the base class automatically.

Why Java specification designers kept the call to base class finalizer responsibility of programmers when the could have easily defined the specification for the same so that we would have less programmer headaque for explicitely calling base class finalizers.

Xinus
  • 29,617
  • 32
  • 119
  • 165
  • Presumably to give you the flexibility to finalize the parent class at any point in the finalizer, not just at the beginning or the end. I don't claim this is useful (often/ever), but it is the only advantage I can see for such a design. – Andy Turner Jul 02 '17 at 14:03
  • Finalizers in Java are not the same as destructors in C++. There are very few guarantees about finalizers, and certainly you can't predict when they'll be called. Read through this [Why would you ever implement finalize()?](https://stackoverflow.com/questions/158174/why-would-you-ever-implement-finalize) – Erwin Bolwidt Jul 02 '17 at 14:03
  • I am aware that there is no gaurantee that finalizers will get invoked but that should not stop them from chaining the finalizers. – Xinus Jul 02 '17 at 14:09
  • 1
    Finalizers were a bad idea from the start, and the focus is now on deprecating and removing them from Java. Not in improving them. https://stuartmarks.wordpress.com/2017/04/17/deprecation-of-object-finalize/ – JB Nizet Jul 02 '17 at 14:15

1 Answers1

-1

"Now we have finalizers in java which would be same as destructors in C++." Uh, no, Java finalizers are nothing at all even remotely the "same as destructors in C++". There's your problem right there.

Finalizers are very special methods really only needed for very limited use cases, like releasing native resources accessed outside normal Java means. They have a devastating effect on garbage collection if used much or wrong. They have special rules.

They're not destructors. Java doesn't have or need destructors.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
  • Maybe not the most polite answer but correct, no need to downvote, finalize really are only for Java's native interface and comparing them to C++ destructorsis wrong. – Derrops Jul 03 '17 at 06:31
  • Finalizers in Java and destructors in C++ have very different semantics. The JLS addresses the lack of guarantee of finalizer order. For that matter, you have no guarantee that a finalizer will even run at all. – Lew Bloch Oct 12 '18 at 22:41