finalize() Method in Java जावा में फाइनलाइज़ मेथड
In Java, when an object holds resources like file handles, fonts, or native system resources, we often need a mechanism to clean them up before the object is destroyed. This process is known as Finalization.
जावा में जब कोई ऑब्जेक्ट फाइल हैंडल, विंडोज फॉन्ट्स जैसे रिसोर्सेज से जुड़ा होता है, तो ऑब्जेक्ट के नष्ट होने से पहले इन रिसोर्सेज को मुक्त करना ज़रूरी होता है। इस प्रक्रिया को Finalization कहते हैं।
finalize()
. You can define this method in your class to perform cleanup tasks before the object is garbage collected.finalize()
होता है। इस मेथड को अपनी क्लास में डिफाइन करके हम वह कार्य कर सकते हैं जो किसी ऑब्जेक्ट के नष्ट होने से ठीक पहले किए जाने चाहिए।🔧 Syntax / प्रारूप:
protected void finalize() throws Throwable {
// Finalization code}
📘 Example / उदाहरण:
class Sample {
int id;Sample(int id) {this.id = id;}protected void finalize() throws Throwable {System.out.println("Object with ID " + id + " is destroyed.");}public static void main(String[] args) {Sample obj1 = new Sample(101);Sample obj2 = new Sample(102);obj1 = null;obj2 = null;System.gc(); // Request garbage collection}}
finalize()
method is used to display a message when the object is destroyed. Although System.gc()
only suggests garbage collection, it may or may not run immediately.finalize()
मेथड तब कॉल होती है जब ऑब्जेक्ट नष्ट होता है। System.gc()
गार्बेज कलेक्टर को कॉल करने का अनुरोध करता है, लेकिन यह तुरंत काम करे, इसकी गारंटी नहीं होती।Note:
-
From Java 9 onwards,
finalize()
is deprecated due to performance and reliability concerns. Alternatives liketry-with-resources
orCleaner
API are recommended. -
जावा 9 से
finalize()
को deprecated कर दिया गया है क्योंकि यह प्रदर्शन और विश्वसनीयता पर नकारात्मक प्रभाव डाल सकता है। इसके स्थान परtry-with-resources
याCleaner
API का उपयोग करना बेहतर माना जाता है।
Comments
Post a Comment