{"id":4393,"date":"2024-10-13T17:58:25","date_gmt":"2024-10-13T12:58:25","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=4393"},"modified":"2024-10-13T17:58:27","modified_gmt":"2024-10-13T12:58:27","slug":"a-detailed-tutorial-on-destructors-in-object-oriented-programming","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2024\/10\/13\/a-detailed-tutorial-on-destructors-in-object-oriented-programming\/","title":{"rendered":"A Detailed Tutorial on Destructors in Object-Oriented Programming"},"content":{"rendered":"\n<p>In object-oriented programming (OOP), managing memory and system resources is a critical task. When we create objects in a program, they occupy memory, and when they are no longer needed, that memory needs to be freed up. This process of releasing resources after their use is typically handled by <strong>destructors<\/strong> in many programming languages like C++. However, Java manages object cleanup differently.<\/p>\n\n\n\n<p>In this tutorial, we\u2019ll explore how <strong>destructors<\/strong> work in languages like C++, and how Java manages resource cleanup using the <strong>Garbage Collector<\/strong> and the <code>finalize()<\/code> method.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is a Destructor?<\/h3>\n\n\n\n<p>A <strong>Destructor<\/strong> is a special method that is automatically invoked when an object is no longer needed or goes out of scope. Its primary responsibility is to release the memory or resources (like file handles, database connections, etc.) that the object was using during its lifetime.<\/p>\n\n\n\n<p>In <strong>C++<\/strong>, destructors are explicitly defined by the programmer and called when the object is destroyed. However, in <strong>Java<\/strong>, destructors are not explicitly defined. Instead, Java provides a built-in garbage collection mechanism that automatically deallocates memory.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Destructor in C++ (for Comparison):<\/h4>\n\n\n\n<p>Here is how destructors work in C++:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Car {\npublic:\n    \/\/ Constructor\n    Car() {\n        cout &lt;&lt; \"Car created.\" &lt;&lt; endl;\n    }\n\n    \/\/ Destructor\n    ~Car() {\n        cout &lt;&lt; \"Car destroyed.\" &lt;&lt; endl;\n    }\n};\n\nint main() {\n    Car myCar;  \/\/ Constructor is called here\n    return 0;   \/\/ Destructor is automatically called here\n}<\/code><\/pre>\n\n\n\n<p>In C++, when the object <code>myCar<\/code> goes out of scope (at the end of the <code>main()<\/code> function), the destructor is called automatically to clean up resources.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Destructor-Like Behavior in Java<\/h3>\n\n\n\n<p>Java does not have destructors in the same way C++ does. Instead, Java uses a <strong>Garbage Collector (GC)<\/strong> to manage memory. The garbage collector automatically removes objects from memory when they are no longer referenced in the program.<\/p>\n\n\n\n<p>This means that in most cases, Java developers do not need to manually free up memory or explicitly define destructors. However, there is a way to handle cleanup tasks before an object is destroyed, and that is by using the <strong><code>finalize()<\/code><\/strong> method.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">The <code>finalize()<\/code> Method in Java:<\/h4>\n\n\n\n<p>The <code>finalize()<\/code> method is called by the garbage collector when it determines that there are no more references to an object. This method can be overridden to provide cleanup operations (like closing files or releasing resources) before the object is actually removed from memory.<\/p>\n\n\n\n<p><strong>Important Note:<\/strong> As of Java 9, the <code>finalize()<\/code> method is <strong>deprecated<\/strong> because of performance issues and unpredictability. Instead, Java provides the <code>try-with-resources<\/code> statement to handle resource cleanup.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example of the <code>finalize()<\/code> Method:<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>class Car {\n    \/\/ Constructor\n    Car() {\n        System.out.println(\"Car created.\");\n    }\n\n    \/\/ finalize method (Deprecated in Java 9 and later)\n    @Override\n    protected void finalize() {\n        System.out.println(\"Car destroyed.\");\n    }\n}\n\npublic class Main {\n    public static void main(String&#91;] args) {\n        Car myCar = new Car();  \/\/ Car object created\n        myCar = null;  \/\/ Now the object is eligible for garbage collection\n\n        \/\/ Suggest garbage collection (not guaranteed)\n        System.gc();   \/\/ The finalize() method might be called here\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Car created.\nCar destroyed.<\/code><\/pre>\n\n\n\n<p>In the above example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>Car<\/code> object is created using the constructor.<\/li>\n\n\n\n<li>The object is made eligible for garbage collection by setting <code>myCar = null;<\/code>.<\/li>\n\n\n\n<li>The <code>System.gc()<\/code> method suggests the JVM to run garbage collection, which might result in the <code>finalize()<\/code> method being called.<\/li>\n<\/ul>\n\n\n\n<p>However, it\u2019s important to note that calling <code>System.gc()<\/code> does <strong>not guarantee<\/strong> immediate garbage collection. The timing of garbage collection is entirely up to the JVM.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Garbage Collection in Java<\/h3>\n\n\n\n<p>Java&#8217;s <strong>Garbage Collector (GC)<\/strong> automatically manages memory by freeing up space when objects are no longer needed. This eliminates the need for manual memory management, which is a common source of bugs in languages like C++.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How the Garbage Collector Works:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Object Creation<\/strong>: When an object is created, memory is allocated to it on the heap.<\/li>\n\n\n\n<li><strong>Reference Counting<\/strong>: As long as there are references to an object, it remains in memory.<\/li>\n\n\n\n<li><strong>Garbage Collection<\/strong>: Once no references to an object exist, the garbage collector marks it for removal.<\/li>\n\n\n\n<li><strong>Memory Cleanup<\/strong>: The garbage collector frees up the memory occupied by the object.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Key Differences Between Destructors in C++ and Java<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Aspect<\/th><th>C++ Destructor<\/th><th>Java Garbage Collection \/ <code>finalize()<\/code><\/th><\/tr><\/thead><tbody><tr><td><strong>Definition<\/strong><\/td><td>Explicitly defined by the programmer<\/td><td>No explicit destructors; <code>finalize()<\/code> can be overridden<\/td><\/tr><tr><td><strong>Invocation<\/strong><\/td><td>Automatically called when object goes out of scope<\/td><td>Called when the garbage collector decides to destroy the object (not guaranteed)<\/td><\/tr><tr><td><strong>Memory Management<\/strong><\/td><td>Manual memory management (with <code>delete<\/code>)<\/td><td>Automatic memory management with the Garbage Collector<\/td><\/tr><tr><td><strong>Best Practice<\/strong><\/td><td>Define destructors for resource cleanup<\/td><td>Use <code>try-with-resources<\/code> for handling resources<\/td><\/tr><tr><td><strong>Deprecation<\/strong><\/td><td>Not applicable<\/td><td><code>finalize()<\/code> is deprecated since Java 9<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>In Java, destructors are replaced by the automatic <strong>Garbage Collection<\/strong> mechanism, which is responsible for managing memory and resources. While Java used to rely on the <code>finalize()<\/code> method for object cleanup, this method is now deprecated in favor of the more efficient <code>try-with-resources<\/code> statement. This ensures that resources like file handles and database connections are properly closed once they are no longer needed.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Key Takeaways:<\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>No explicit destructors in Java<\/strong>: Memory management is handled by the garbage collector.<\/li>\n\n\n\n<li><strong><code>finalize()<\/code> is deprecated<\/strong>: Do not use <code>finalize()<\/code> for resource management; instead, use <code>try-with-resources<\/code>.<\/li>\n\n\n\n<li><strong>Automatic cleanup<\/strong>: Java\u2019s garbage collector ensures that objects are destroyed when they are no longer referenced, simplifying memory management for developers.<\/li>\n<\/ol>\n\n\n\n<p>By understanding how Java handles object cleanup, developers can write efficient and resource-friendly code without worrying about memory leaks and resource mismanagement.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In object-oriented programming (OOP), managing memory and system resources is a critical task. When we create objects in a program, they occupy memory, and when they are no longer needed, that memory needs to be freed up. This process of releasing resources after their use is typically handled by destructors in many programming languages like C++. However, Java manages object cleanup differently. In this tutorial, we\u2019ll explore how destructors work in languages like C++, and how Java manages resource cleanup&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2024\/10\/13\/a-detailed-tutorial-on-destructors-in-object-oriented-programming\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":4395,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[602],"tags":[629,612,603],"class_list":["post-4393","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-object-oriented-programing-oop","tag-destructor","tag-java","tag-oop"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/10\/Static-Data-Members-and-Functions-Java-1-jpg.webp?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-18R","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4393","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=4393"}],"version-history":[{"count":2,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4393\/revisions"}],"predecessor-version":[{"id":4396,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4393\/revisions\/4396"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/4395"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=4393"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=4393"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=4393"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}