{"id":5901,"date":"2023-11-06T12:54:24","date_gmt":"2023-11-06T19:54:24","guid":{"rendered":"https:\/\/ioflood.com\/blog\/?p=5901"},"modified":"2024-03-05T18:42:07","modified_gmt":"2024-03-06T01:42:07","slug":"method-overriding-in-java","status":"publish","type":"post","link":"https:\/\/ioflood.com\/blog\/method-overriding-in-java\/","title":{"rendered":"Method Overriding in Java: In-Depth Tutorial"},"content":{"rendered":"<div class=\"wp-block-image\">\n<figure class=\"alignright size-full is-resized\"><img decoding=\"async\" src=\"https:\/\/ioflood.com\/blog\/wp-content\/uploads\/2023\/11\/method_overriding_in_java_cog_wheel-300x300.jpg\" alt=\"method_overriding_in_java_cog_wheel\" width=\"300\" height=\"300\" title=\"\"><\/figure>\n<\/div>\n<p>Are you finding it challenging to grasp the concept of method overriding in Java? You&#8217;re not alone. Many developers find themselves puzzled when it comes to handling method overriding, but we&#8217;re here to help.<\/p>\n<p>Think of method overriding in Java as a skilled actor taking on different roles. A method in Java can take on different forms in subclasses, providing a versatile and handy tool for various tasks.<\/p>\n<p><strong>In this guide, we&#8217;ll walk you through the process of mastering method overriding in Java<\/strong>, from its basic usage to more advanced techniques, as well as alternative approaches. We&#8217;ll cover everything from the basics of method overriding to more complex scenarios, along with common issues and their solutions.<\/p>\n<p>Let&#8217;s dive in and start mastering method overriding in Java!<\/p>\n<h2>TL;DR: What is Method Overriding in Java?<\/h2>\n<blockquote><p>\n  Method overriding in Java is when a subclass provides a specific implementation of a method that is already provided by its parent class. This allows the subclass to inherit the methods of the parent class and modify them as needed.\n<\/p><\/blockquote>\n<p>Here&#8217;s a simple example:<\/p>\n<pre><code class=\"language-java line-numbers\">class Parent {\n    void show() {\n        System.out.println('Parent's show()');\n    }\n}\n\nclass Child extends Parent {\n    void show() {\n        System.out.println('Child's show()');\n    }\n}\n\n\/\/ Create an instance of Child\nChild child = new Child();\n\/\/ Call the show method\nchild.show();\n\n\/\/ Output:\n\/\/ 'Child's show()'\n<\/code><\/pre>\n<p>In this example, we have a <code>Parent<\/code> class with a <code>show()<\/code> method, and a <code>Child<\/code> class that extends the <code>Parent<\/code> class and overrides the <code>show()<\/code> method. When we create an instance of <code>Child<\/code> and call the <code>show()<\/code> method, the overridden method in the <code>Child<\/code> class is executed, not the one in the <code>Parent<\/code> class.<\/p>\n<blockquote><p>\n  This is a basic example of method overriding in Java, but there&#8217;s much more to learn about this powerful feature. Continue reading for a more detailed understanding and advanced usage scenarios.\n<\/p><\/blockquote>\n<h2>Unraveling Method Overriding in Java<\/h2>\n<p>Method overriding in Java is a core concept of object-oriented programming that allows a subclass to provide a different implementation of a method that is already provided by its parent class. This is a powerful feature that allows developers to write flexible and maintainable code.<\/p>\n<p>Let&#8217;s consider a basic example to understand how method overriding works in Java:<\/p>\n<pre><code class=\"language-java line-numbers\">class Animal {\n    void sound() {\n        System.out.println('Animals make sounds');\n    }\n}\n\nclass Dog extends Animal {\n    void sound() {\n        System.out.println('Dogs bark');\n    }\n}\n\n\/\/ Create an instance of Dog\nDog dog = new Dog();\n\/\/ Call the sound method\ndog.sound();\n\n\/\/ Output:\n\/\/ 'Dogs bark'\n<\/code><\/pre>\n<p>In this example, the <code>Animal<\/code> class has a method named <code>sound()<\/code>. The <code>Dog<\/code> class, which is a subclass of <code>Animal<\/code>, overrides the <code>sound()<\/code> method. When we create an instance of <code>Dog<\/code> and call the <code>sound()<\/code> method, the overridden method in the <code>Dog<\/code> class is executed, not the one in the <code>Animal<\/code> class.<\/p>\n<h3>Advantages of Method Overriding<\/h3>\n<p>Method overriding provides several benefits:<\/p>\n<ul>\n<li><strong>Code Reusability<\/strong>: We can use the method from the parent class and modify it in the subclass as needed, which promotes code reusability.<\/li>\n<li><strong>Flexibility<\/strong>: It allows subclasses to behave differently. In our example, different animal classes can provide different implementations of the <code>sound()<\/code> method.<\/li>\n<li><strong>Abstraction<\/strong>: The user does not need to know which method implementation is being used. They can simply call the <code>sound()<\/code> method on an animal object, and the correct method will be executed.<\/li>\n<\/ul>\n<h3>Potential Pitfalls<\/h3>\n<p>While method overriding is a powerful feature, it&#8217;s important to be aware of potential pitfalls:<\/p>\n<ul>\n<li><strong>Method Signature<\/strong>: The method in the subclass must have the exact same name, return type, and parameters as the method in the parent class. If these do not match, the method will not be overridden.<\/li>\n<li><strong>Access Level<\/strong>: The access level cannot be more restrictive in the subclass. For example, if the method in the parent class is <code>public<\/code>, the overridden method in the subclass cannot be <code>private<\/code> or <code>protected<\/code>.<\/li>\n<\/ul>\n<p>Understanding these basics will set the foundation for further exploration into the world of method overriding in Java.<\/p>\n<h2>Diving Deeper into Method Overriding<\/h2>\n<p>As you become more comfortable with the concept of method overriding in Java, it&#8217;s time to delve into its more complex uses. Let&#8217;s discuss when to use the @Override annotation, how method overriding works with access modifiers, and how it interacts with exception handling.<\/p>\n<h3>The @Override Annotation<\/h3>\n<p>The @Override annotation is a handy tool in Java that ensures that a method is actually overriding a method from a superclass. If it&#8217;s not, the compiler will throw an error.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<pre><code class=\"language-java line-numbers\">class Animal {\n    void sound() {\n        System.out.println('Animals make sounds');\n    }\n}\n\nclass Dog extends Animal {\n    @Override\n    void sound() {\n        System.out.println('Dogs bark');\n    }\n}\n\n\/\/ Create an instance of Dog\nDog dog = new Dog();\n\/\/ Call the sound method\ndog.sound();\n\n\/\/ Output:\n\/\/ 'Dogs bark'\n<\/code><\/pre>\n<p>In this example, the <code>sound()<\/code> method in the <code>Dog<\/code> class is annotated with @Override, which tells the compiler that the method should override a method in the superclass. If the <code>sound()<\/code> method in the <code>Animal<\/code> class didn&#8217;t exist or had a different method signature, the compiler would throw an error.<\/p>\n<h3>Method Overriding and Access Modifiers<\/h3>\n<p>When overriding methods in Java, the access level can&#8217;t be more restrictive in the subclass. For example, if the method in the parent class is <code>public<\/code>, the overridden method in the subclass can&#8217;t be <code>private<\/code> or <code>protected<\/code>. However, it can be <code>public<\/code>.<\/p>\n<h3>Method Overriding and Exception Handling<\/h3>\n<p>When it comes to exception handling, the overridden method in the subclass can&#8217;t throw a broader checked exception than the method in the parent class. However, it can throw narrower checked exceptions, any unchecked exceptions, or no exceptions at all.<\/p>\n<p>By understanding these advanced concepts, you&#8217;ll be able to utilize method overriding in Java more effectively and write more flexible and maintainable code.<\/p>\n<h2>Exploring Alternatives: Method Overloading vs Method Overriding<\/h2>\n<p>While method overriding is a powerful feature in Java, it&#8217;s not the only way to modify the behavior of methods. Another related concept is method overloading, which has its own unique uses and benefits. Understanding the differences between these two concepts can help you choose the right tool for the job.<\/p>\n<h3>What is Method Overloading?<\/h3>\n<p>Method overloading in Java occurs when two or more methods in the same class have the same name but different parameters. This allows multiple methods to perform similar tasks but with different input types or numbers of inputs.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<pre><code class=\"language-java line-numbers\">class Calculator {\n    int add(int a, int b) {\n        return a + b;\n    }\n\n    int add(int a, int b, int c) {\n        return a + b + c;\n    }\n}\n\n\/\/ Create an instance of Calculator\nCalculator calculator = new Calculator();\n\/\/ Call the add method\nSystem.out.println(calculator.add(2, 3));  \/\/ Output: 5\nSystem.out.println(calculator.add(2, 3, 4));  \/\/ Output: 9\n<\/code><\/pre>\n<p>In this example, the <code>Calculator<\/code> class has two <code>add()<\/code> methods. One takes two parameters and the other takes three. When we call the <code>add()<\/code> method with two or three arguments, the appropriate method is executed.<\/p>\n<h3>Comparing Method Overloading and Method Overriding<\/h3>\n<p>While both method overloading and method overriding allow us to modify the behavior of methods, they serve different purposes and have their own benefits and drawbacks:<\/p>\n<ul>\n<li><strong>Method Overriding<\/strong> allows a subclass to provide a different implementation of a method that is already provided by its parent class. This is useful when we want subclasses to share a common interface but behave differently.<\/p>\n<\/li>\n<li>\n<p><strong>Method Overloading<\/strong> allows a class to have multiple methods with the same name but different parameters. This is useful when we want a method to perform similar tasks but with different types or numbers of inputs.<\/p>\n<\/li>\n<\/ul>\n<p>Understanding these differences can help you make more informed decisions when designing your classes and methods in Java.<\/p>\n<h2>Navigating Troubles with Method Overriding<\/h2>\n<p>As with any programming concept, method overriding in Java can present its own set of challenges. Let&#8217;s go through some common errors you might encounter and how to solve them.<\/p>\n<h3>Incorrect Method Signature<\/h3>\n<p>One common error is incorrect method signature. Remember, the method in the subclass must have the exact same name, return type, and parameters as the method in the parent class. If these do not match, the method will not be overridden, and the superclass&#8217;s method will be called instead.<\/p>\n<p>Consider this example:<\/p>\n<pre><code class=\"language-java line-numbers\">class Parent {\n    void display() {\n        System.out.println('Parent's display()');\n    }\n}\n\nclass Child extends Parent {\n    void display(int num) {\n        System.out.println('Child's display() ' + num);\n    }\n}\n\n\/\/ Create an instance of Child\nChild child = new Child();\n\/\/ Call the display method\nchild.display();\n\n\/\/ Output:\n\/\/ 'Parent's display()'\n<\/code><\/pre>\n<p>In this example, we intended to override the <code>display()<\/code> method in the <code>Child<\/code> class, but we added an extra parameter. This changes the method signature, and so the <code>display()<\/code> method in the <code>Parent<\/code> class is called instead.<\/p>\n<h3>More Restrictive Access Level<\/h3>\n<p>Another common error is making the access level of the overridden method more restrictive. The access level can&#8217;t be more restrictive in the subclass. For example, if the method in the parent class is <code>public<\/code>, the overridden method in the subclass can&#8217;t be <code>private<\/code> or <code>protected<\/code>.<\/p>\n<p>Here&#8217;s an example that demonstrates this error:<\/p>\n<pre><code class=\"language-java line-numbers\">class Parent {\n    public void show() {\n        System.out.println('Parent's show()');\n    }\n}\n\nclass Child extends Parent {\n    private void show() {\n        System.out.println('Child's show()');\n    }\n}\n\n\/\/ This code will not compile because\n\/\/ the show() method in the Child class\n\/\/ is more restrictive than in the Parent class.\n<\/code><\/pre>\n<p>In this example, the <code>show()<\/code> method in the <code>Child<\/code> class is <code>private<\/code>, which is more restrictive than the <code>public<\/code> <code>show()<\/code> method in the <code>Parent<\/code> class. This code will not compile.<\/p>\n<h3>Best Practices and Optimization<\/h3>\n<p>When using method overriding in Java, here are some best practices to keep in mind:<\/p>\n<ul>\n<li><strong>Use the @Override annotation<\/strong>: This helps catch errors at compile time if a method intended to override a superclass&#8217;s method does not do so correctly.<\/li>\n<li><strong>Follow the Liskov Substitution Principle (LSP)<\/strong>: Subclasses should be substitutable for their superclass without causing issues. This means the behavior of the overridden method should not contradict the behavior of the superclass&#8217;s method.<\/li>\n<li><strong>Don&#8217;t override methods marked as final<\/strong>: The <code>final<\/code> keyword in Java is used to restrict users from changing the value (for variables), changing the class (for classes), or overriding the method (for methods).<\/li>\n<\/ul>\n<p>By understanding these common errors and best practices, you can avoid pitfalls and utilize method overriding in Java more effectively.<\/p>\n<h2>Understanding Inheritance: The Foundation of Method Overriding<\/h2>\n<p>Before we can fully grasp the concept of method overriding in Java, we need to understand the principle of inheritance, which is fundamental to method overriding.<\/p>\n<p>Inheritance in Java is a mechanism where one class acquires the properties (fields and methods) of another. With the use of inheritance, information is managed in a hierarchical order. The class which inherits the properties of another is known as the subclass (or derived class), and the class whose properties are inherited is known as the superclass (or base class).<\/p>\n<p>Here&#8217;s a simple example:<\/p>\n<pre><code class=\"language-java line-numbers\">class Animal {\n    void eat() {\n        System.out.println('Eating...');\n    }\n}\n\nclass Dog extends Animal {\n}\n\n\/\/ Create an instance of Dog\nDog dog = new Dog();\n\/\/ Call the eat method\ndog.eat();\n\n\/\/ Output:\n\/\/ 'Eating...'\n<\/code><\/pre>\n<p>In this example, the <code>Dog<\/code> class inherits from the <code>Animal<\/code> class. This means that a <code>Dog<\/code> object can use the <code>eat()<\/code> method defined in the <code>Animal<\/code> class. Inheritance is a way to promote code reuse and is a key part of object-oriented programming.<\/p>\n<h2>Object-Oriented Principles and Method Overriding<\/h2>\n<p>Method overriding is a perfect example of the &#8216;Polymorphism&#8217; principle in object-oriented programming. Polymorphism allows objects of different classes to be treated as objects of a common superclass. With method overriding, a subclass can provide a different implementation of a method that is already defined in its superclass, which allows the same method call to behave differently depending on whether it&#8217;s called on an object of the superclass or an object of the subclass.<\/p>\n<p>By understanding inheritance and the principles of object-oriented programming, you can see how method overriding fits into the bigger picture of Java programming.<\/p>\n<h2>Method Overriding in the Real World<\/h2>\n<p>Method overriding in Java is not just a theoretical concept, it&#8217;s a practical tool that developers use in real-world applications. Let&#8217;s explore how method overriding can be used to create customizable software components and implement polymorphism in Java.<\/p>\n<h3>Customizable Software Components<\/h3>\n<p>In software development, it&#8217;s common to have components that share a lot of common features but also have some specific behaviors. By using method overriding, you can create a base class with all the common features and then create subclasses that override specific methods to customize their behavior.<\/p>\n<p>For example, consider a software for a library. You might have a <code>Book<\/code> class with methods like <code>borrow()<\/code>, <code>return()<\/code>, and <code>renew()<\/code>. If you want to introduce different types of books, like <code>RegularBook<\/code> and <code>ReferenceBook<\/code>, you can create these as subclasses of <code>Book<\/code> and override the methods as needed. For instance, <code>ReferenceBook<\/code> might override the <code>borrow()<\/code> method because reference books can&#8217;t be borrowed.<\/p>\n<h3>Implementing Polymorphism<\/h3>\n<p>Polymorphism is a core concept in object-oriented programming that allows objects to take on many forms. Method overriding is a key way to implement polymorphism in Java. By overriding methods, subclasses can provide their own unique behaviors while still being treated as instances of the superclass.<\/p>\n<p>For example, consider a <code>Shape<\/code> class with a <code>draw()<\/code> method. You can create subclasses like <code>Circle<\/code>, <code>Square<\/code>, and <code>Triangle<\/code>, each overriding the <code>draw()<\/code> method to draw the appropriate shape. When you call the <code>draw()<\/code> method on a <code>Shape<\/code> reference, the correct method will be called based on the actual object type, even though the reference type is <code>Shape<\/code>. This is polymorphism in action.<\/p>\n<h3>Further Resources for Method Overriding<\/h3>\n<p>If you&#8217;re interested in learning more about method overriding in Java, here are some resources that you might find helpful:<\/p>\n<ul>\n<li><a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/ioflood.com\/blog\/java-methods\/\">Importance of Java Methods in Programming<\/a> &#8211; Gain practical insights into Java methods for effective coding.<\/p>\n<\/li>\n<li>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/ioflood.com\/blog\/method-signature-java\/\">Understanding Method Declaration in Java<\/a> &#8211; Explore Java method signatures for specifying method names, return types, and parameters.<\/p>\n<\/li>\n<li>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/ioflood.com\/blog\/public-static-void-main-string-args\/\">Exploring Java Main Method Signature<\/a> &#8211; Tthe anatomy of the public static void main(String[] args) method in Java.<\/p>\n<\/li>\n<li>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/java\/IandI\/override.html\" target=\"_blank\" rel=\"noopener\">Oracle Java Documentation<\/a> provides a thorough explanation of method overriding.<\/p>\n<\/li>\n<li>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/www.geeksforgeeks.org\/overriding-in-java\/\" target=\"_blank\" rel=\"noopener\">Geeks for Geeks Java Method Overriding<\/a> offers a detailed guide on method overriding in Java.<\/p>\n<\/li>\n<li>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"https:\/\/www.javatpoint.com\/runtime-polymorphism-in-java\" target=\"_blank\" rel=\"noopener\">JavaTpoint Method Overriding in Java<\/a> goes over method overriding complete with diagrams and examples.<\/p>\n<\/li>\n<\/ul>\n<h2>Wrapping Up: Method Overriding in Java<\/h2>\n<p>In this comprehensive guide, we&#8217;ve journeyed through the concept of method overriding in Java, a fundamental feature in object-oriented programming that allows a subclass to provide a different implementation of a method that is already provided by its parent class.<\/p>\n<p>We began with the basics, clarifying what method overriding is and providing simple examples for beginners. We then ventured into more advanced territory, discussing the use of the @Override annotation, how method overriding works with access modifiers, and its interaction with exception handling. Along the way, we tackled common challenges you might face when using method overriding, such as incorrect method signature and more restrictive access level, providing you with solutions for each issue.<\/p>\n<p>We also looked at alternative approaches to method modification, comparing method overriding with method overloading. Here&#8217;s a quick comparison of these concepts:<\/p>\n<table>\n<thead>\n<tr>\n<th>Concept<\/th>\n<th>Description<\/th>\n<th>Use Case<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Method Overriding<\/td>\n<td>Allows a subclass to provide a different implementation of a method from its parent class<\/td>\n<td>When you want subclasses to share a common interface but behave differently<\/td>\n<\/tr>\n<tr>\n<td>Method Overloading<\/td>\n<td>Allows a class to have multiple methods with the same name but different parameters<\/td>\n<td>When you want a method to perform similar tasks but with different types or numbers of inputs<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Whether you&#8217;re just starting out with method overriding or you&#8217;re looking to level up your Java programming skills, we hope this guide has given you a deeper understanding of method overriding and its capabilities.<\/p>\n<p>With its ability to allow subclasses to behave differently and promote code reusability, method overriding is a powerful tool in Java programming. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Are you finding it challenging to grasp the concept of method overriding in Java? You&#8217;re not alone. Many developers find themselves puzzled when it comes to handling method overriding, but we&#8217;re here to help. Think of method overriding in Java as a skilled actor taking on different roles. A method in Java can take on [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":8690,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[154,121],"tags":[],"class_list":["post-5901","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","category-programming-coding","cat-154-id","cat-121-id","has_thumb"],"_links":{"self":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts\/5901","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/comments?post=5901"}],"version-history":[{"count":9,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts\/5901\/revisions"}],"predecessor-version":[{"id":8683,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/posts\/5901\/revisions\/8683"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/media\/8690"}],"wp:attachment":[{"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/media?parent=5901"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/categories?post=5901"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ioflood.com\/blog\/wp-json\/wp\/v2\/tags?post=5901"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}