What is method overriding in Java – Example Tutorial

Method overriding in Java
Method overriding in Java is a concept based on polymorphism OOPS concept which allows the programmer to create two methods with the same name and method signature on the interface and its various implementation and the actual method is called at runtime depending upon the type of an object at runtime. Method overriding allows you to write flexible and extensible code in Java because you can introduce new functionality with the minimal code change. Method overriding is different than the method overloading in Java which we have discussed in the last article.

In method overloading, Only name of two overloaded methods are the same but method signature must be different while in the method overriding, the method signature must be the same. method overriding represent true polymorphic behavior, where the only name needs to be the same underlying method logic can be different.

In this Java tutorial, we will see What is method overriding in Java, Rules to override a method in Java and an example of How to override a method in Java. We won't discuss difference between method overloading and overriding in Java, maybe some other post.




Rules of method overriding in Java

What is method overriding in Java with Example There are few rules which needs to be followed while overriding any method in Java, failure to follow these rules results in a compile-time error in Java.


1) The first and most important rule regarding method overriding in Java is that you can only override a method in a subclass. You can not override the method in the same class.

2) A second important rule of method overriding in Java that name and signature of method must be the same in Super class and Sub class or in the interface and its implementation.

3) The third rule to override a method in Java is that the overriding method can not reduce the accessibility of the overridden method in Java. For example, if the overridden method is public than the overriding method can not be protected, private or package-private; 

But the opposite is true overriding method can increase the accessibility of method in Java, i.e. if the overridden method is protected than The overriding method can be protected or public.




4) Another worth noting rule of method overriding in Java is that the overriding  method can not throw checked Exception which is higher in the hierarchy than the overridden method. This means if the overridden method throws IOException than the overriding method can not throw java.lang.Exception in its throws clause because of java.lang.Exception comes higher than IOException in Exception hierarchy. 

This rule doesn't apply to RuntimeException in Java, which is not even needed to be declared in a throws clause in Java.


5) You can not override private, static and final the method in Java. private and static method are bonded during compile time using static binding in Java and doesn't resolve during runtime. the overriding the final method in Java is a compile-time error. Though private and static methods can be hidden if you declare another method with the same and signature in the subclass.

6) The overridden method is called using dynamic binding in Java at runtime based upon the type of Object. As shown in the following example of method overriding in Java.

7) If you are extending the abstract class or implementing interface than you need to override all abstract methods unless your class is not abstract. an abstract method can only be used by using method overriding.

8) Always use @Override annotation while the overriding method in Java. Though this is not a rule but its one of the best Java coding practices to follow. From Java 6 you can use @Override annotation on a method inherited from the interface as well.


Method Overriding Example in Java

Now we know what is method overriding in Java and rules of method overriding, It's time to see an example of how to override a method in Java. In this example, we have used the Runnable interface which has an abstract run() method. We have two class Task and PeriodicTask which implements the Runnable interface and override run method. 

For the purpose of demonstrating how method overriding works in Java we are calling run() method in same thread, which you should not, see difference between run and start method to know why. Because run() is overridden in two separate class, call to run() method will be resolved during runtime depending upon type of Object.

/**
 *
 * Java program to demonstrate how to override a method in Java.
 * Overridden method are resolved during runtime based upon the type of object
 *
 * @author Javin
 */

public class CollectionTest {
 
    public static void main(String args[]) {
 
      Runnable task = new Task();
      task.run(); //call overridden method in Task
   
      task = new PeriodicTask();
      task.run(); //calls overridden method in PeriodicTas

    }
 
 
}

class Task implements Runnable{

    @Override
    public void run() {
        System.out.println("Run method overridden in Task class");
    }
 
}

class PeriodicTask extends Task{
 
    @Override
    public void run() {
        System.err.println("overridden method run() in PeriodicTask class");
    }
}

Output:
Run method is overridden in Task class
overridden method run() in PeriodicTask class


That's all on What is method overriding in Java, Rules of method overriding in Java, and an example of How to override a method in Java. In summary, remember to override all abstract methods while extending form abstract class or implementing the interface. 

The overridden method is also slower as compared to static and final methods because of dynamic binding but it provides you flexibility, many popular Object-oriented design principles are based upon method overriding in Java.

Further Learning
SOLID Principles of Object-Oriented Design
Absolute Introduction to Object-Oriented Programming in Java
Java - Object-Oriented Programming [For Absolute Beginners]

Other Java tutorials you may like
10 Java Coding Interview Questions and Answers for Java beginners.


Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious about learning object-oriented programming and looking for a free online course to start with then you can also check this FREE Object Oriented Programming (OOPs) for JAVA Interviews course on Udemy. It's completely free and you just need a free Udemy account to join this course. 

5 comments:

  1. From Java 1.5 onwards, an overridding method in Java can return sub-class of return type of overridden method. Which means if your original method return java.lang.Object than a method which overrides this in subclass can return object of Subclass. for example

    public class Shape{

    public Shape getShape(){
    return new Shape();
    }
    }

    public class Circle{

    @OVerride
    public Circle getShape(){
    return new Circle();
    }

    }
    is legal in Java 5, 6 and Java 7.

    ReplyDelete
  2. What is the advantage of @override annotation?

    ReplyDelete
    Replies
    1. This is to make sure that override is happening correctly and later on if super class changes thn it should reflect in subclasses.

      Delete
  3. Heading should be "Method Overriding Example in Java" and not "Method Overloading Example in Java".

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.