{"id":4740,"date":"2024-11-11T15:10:58","date_gmt":"2024-11-11T10:10:58","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=4740"},"modified":"2024-11-11T15:14:28","modified_gmt":"2024-11-11T10:14:28","slug":"difference-between-method-function-overloading-and-overriding-polymorphism","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2024\/11\/11\/difference-between-method-function-overloading-and-overriding-polymorphism\/","title":{"rendered":"Difference between Method\/Function Overloading and  Overriding (Polymorphism)"},"content":{"rendered":"\n<p>Polymorphism, a foundational concept in object-oriented programming (OOP), allows methods or functions to process objects differently based on their data type or class. In Java, polymorphism enables one interface to be used for a general class of actions, allowing a program to behave dynamically depending on the context. This tutorial explains polymorphism, covers its types and benefits, and illustrates its implementation in Java.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Polymorphism?<\/h3>\n\n\n\n<p>Polymorphism, from Greek words meaning &#8220;many forms,&#8221; refers to the ability of an object to take on multiple forms. It allows a single function or method to work differently based on the object calling it, which enhances code flexibility and reusability. In Java, polymorphism can be achieved through:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Method Overloading (Compile-Time Polymorphism)<\/strong><\/li>\n\n\n\n<li><strong>Method Overriding (Run-Time Polymorphism)<\/strong><\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">1. Compile-Time Polymorphism (Method Overloading)<\/h3>\n\n\n\n<p>In <strong>function overloading<\/strong>, multiple methods in the same class have the same name but different parameter lists. The compiler determines which method to call based on the method signature. This decision is made during compilation, hence the term &#8220;compile-time polymorphism.&#8221;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example of Method Overloading<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>class Calculator {\n    \/\/ Method to add two integers\n    int add(int a, int b) {\n        return a + b;\n    }\n\n    \/\/ Method to add three integers\n    int add(int a, int b, int c) {\n        return a + b + c;\n    }\n\n    \/\/ Method to add two double values\n    double add(double a, double b) {\n        return a + b;\n    }\n}\n\npublic class TestCalculator {\n    public static void main(String&#91;] args) {\n        Calculator calculator = new Calculator();\n\n        System.out.println(\"Add two integers: \" + calculator.add(5, 10));\n        System.out.println(\"Add three integers: \" + calculator.add(5, 10, 15));\n        System.out.println(\"Add two doubles: \" + calculator.add(5.5, 10.5));\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>Calculator<\/code> class defines three <code>add<\/code> methods with different parameters.<\/li>\n\n\n\n<li>The compiler selects the correct method based on the argument type and number, providing flexibility without altering method names.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">2. Run-time polymorphism (Method Overriding)<\/h3>\n\n\n\n<p>In <strong>method overriding<\/strong>, a subclass provides a specific implementation of a method that is already defined in its superclass. This type of polymorphism is resolved during runtime. Run-time polymorphism supports the concept of &#8220;one interface, many methods&#8221; by allowing different subclasses to provide their unique implementations of a superclass method.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example of Method Overriding<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>class Car {\n    void drive() {\n        System.out.println(\"The car is driving.\");\n    }\n}\n\nclass Sedan extends Car {\n    @Override\n    void drive() {\n        System.out.println(\"The Sedan run smoothly on the highway.\");\n    }\n}\n\nclass SUV extends Car {\n    @Override\n    void drive() {\n        System.out.println(\"The SUV run smoothly on the highway.\");\n    }\n}\n\nclass SportsCar extends Car {\n    @Override\n    void drive() {\n        System.out.println(\"The SportsCar zooms at high speed on the track.\");\n    }\n}\n\npublic class CarTest {\n    public static void main(String&#91;] args) {\n        Car mySedan = new Sedan();\n        Car mySUV = new SUV();\n        Car mySportsCar = new SportsCar();\n        \n        mySedan.drive();     \n        mySUV.drive();       \n        mySportsCar.drive(); \n    }\n}\n<\/code><\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>Car<\/code> superclass provides a generic <code>drive<\/code> method. Each subclass (Sedan, SUV, and SportsCar) overrides drive with its unique behaviour. Using a Car reference for different car types enables polymorphic behaviour at runtime through <strong>dynamic method dispatch<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Upcasting and Dynamic Method Dispatch<\/h3>\n\n\n\n<p>Java uses <strong>upcasting<\/strong> to handle method calls at runtime. When a superclass reference points to a subclass object, it can call overridden methods in the subclass based on the object&#8217;s actual type. This process is known as <strong>dynamic method dispatch<\/strong> and is a key feature of runtime polymorphism.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Car Suv = new Car(); \/\/ Upcasting\nSuv.drive(); \/\/ Calls drive method due to dynamic method dispatch<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits of Polymorphism<\/h3>\n\n\n\n<p><strong>Code Reusability<\/strong>: Reusable code is a major advantage of polymorphism. Methods with the same name can work with different types or classes, reducing code redundancy.<\/p>\n\n\n\n<p><strong>Extensibility<\/strong>: New classes and methods can be added with minimal changes to existing code, as polymorphic behavior is inherently adaptable.<\/p>\n\n\n\n<p><strong>Maintainability<\/strong>: A polymorphic approach improves code organization, making the codebase easier to manage and maintain.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Real-World Example: A Payment System<\/h3>\n\n\n\n<p>Consider a payment system with different payment methods like <strong>CreditCard<\/strong> and <strong>PayPal<\/strong>. Polymorphism allows creating a general <code>Payment<\/code> interface that can handle different payment methods dynamically.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>interface Payment {\n    void makePayment(double amount);\n}\n\nclass CreditCard implements Payment {\n    @Override\n    public void makePayment(double amount) {\n        System.out.println(\"Paid \" + amount + \" with Credit Card.\");\n    }\n}\n\nclass PayPal implements Payment {\n    @Override\n    public void makePayment(double amount) {\n        System.out.println(\"Paid \" + amount + \" via PayPal.\");\n    }\n}\n\npublic class PaymentSystem {\n    public static void main(String&#91;] args) {\n        Payment payment1 = new CreditCard();\n        Payment payment2 = new PayPal();\n\n        payment1.makePayment(100.00);\n        payment2.makePayment(250.00);\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this system:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Both <code>CreditCard<\/code> and <code>PayPal<\/code> classes implement the <code>Payment<\/code> interface.<\/li>\n\n\n\n<li>By using the <code>Payment<\/code> reference, the program dynamically decides the payment method, showcasing polymorphism in action.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Differences Between Method Overloading and Method Overriding<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Aspect<\/th><th>Method Overloading<\/th><th>Method Overriding<\/th><\/tr><\/thead><tbody><tr><td>Purpose<\/td><td>To define multiple methods with the same name but different parameters.<\/td><td>To provide a specific implementation in a subclass for a superclass method.<\/td><\/tr><tr><td>Binding<\/td><td>Compile-time<\/td><td>Run-time<\/td><\/tr><tr><td>Scope<\/td><td>Within the same class<\/td><td>Across a superclass-subclass hierarchy<\/td><\/tr><tr><td>Return Type<\/td><td>Can differ<\/td><td>Must be the same or covariant<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Polymorphism in Interfaces<\/h3>\n\n\n\n<p>Java interfaces support polymorphism by allowing a class to implement multiple interfaces. This approach can lead to flexible and extensible designs.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>interface Drawable {\n    void draw();\n}\n\nclass Circle implements Drawable {\n    public void draw() {\n        System.out.println(\"Drawing a Circle\");\n    }\n}\n\nclass Square implements Drawable {\n    public void draw() {\n        System.out.println(\"Drawing a Square\");\n    }\n}\n\npublic class ShapeTest {\n    public static void main(String&#91;] args) {\n        Drawable shape1 = new Circle();\n        Drawable shape2 = new Square();\n\n        shape1.draw(); \/\/ Outputs \"Drawing a Circle\"\n        shape2.draw(); \/\/ Outputs \"Drawing a Square\"\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practices for Using Polymorphism in Java<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Favor Interfaces<\/strong>: Use interfaces to define generic behaviors, allowing multiple implementations and promoting extensibility.<\/li>\n\n\n\n<li><strong>Choose Clear Method Names<\/strong>: For overloaded methods, make parameter types and method purposes clear to avoid confusion.<\/li>\n\n\n\n<li><strong>Use <code>@Override<\/code> Annotation<\/strong>: This helps ensure methods are correctly overridden and improves code readability.<\/li>\n\n\n\n<li><strong>Keep Methods Specific to Purpose<\/strong>: Avoid excessive method overloading that could reduce code clarity.<\/li>\n<\/ol>\n\n\n\n<p><a href=\"https:\/\/www.canva.com\/design\/DAGWKB0CnZ4\/cn2Rh5adZT3n_8yOLX7d1g\/view?utm_content=DAGWKB0CnZ4&amp;utm_campaign=designshare&amp;utm_medium=link&amp;utm_source=editor\" target=\"_blank\" rel=\"noopener\" title=\"\">Visit the detailed presentation.<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Summary<\/h3>\n\n\n\n<p>Polymorphism in Java is a robust tool for creating flexible, reusable, and maintainable code. By supporting both compile-time (method overloading) and run-time (method overriding) polymorphism, Java allows methods to adapt based on context, empowering developers to create more dynamic applications.<\/p>\n\n\n\n<p>This detailed tutorial follows your comprehensive guide\u2019s structure by focusing on real-world examples, in-depth explanations, and coding illustrations.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Polymorphism, a foundational concept in object-oriented programming (OOP), allows methods or functions to process objects differently based on their data type or class. In Java, polymorphism enables one interface to be used for a general class of actions, allowing a program to behave dynamically depending on the context. This tutorial explains polymorphism, covers its types and benefits, and illustrates its implementation in Java. What is Polymorphism? Polymorphism, from Greek words meaning &#8220;many forms,&#8221; refers to the ability of an object&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2024\/11\/11\/difference-between-method-function-overloading-and-overriding-polymorphism\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":4749,"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":[612,603,634,635,608],"class_list":["post-4740","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-object-oriented-programing-oop","tag-java","tag-oop","tag-overloading","tag-overriding","tag-polymorphism"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/Object-Oriented-Programing-jpg.webp?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-1es","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4740","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=4740"}],"version-history":[{"count":7,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4740\/revisions"}],"predecessor-version":[{"id":4753,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4740\/revisions\/4753"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/4749"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=4740"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=4740"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=4740"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}