Method Overriding

    Method Overriding

    If you define the same method in the child class as the parent class, this concept is called overriding. The concept of overriding allows you to provide an implementation of the method in the child class which is already present in the parent class. With the help of the method overriding you can implement runtime polymorphism.

    Method overriding rules-

    Below are some rules that need to be kept in mind while implementing overriding-

    • The method name should be the same as the parent class.
    • The implemented method should have the same number and data type of the parameters.
    • There should be an IS-A relationship to achieve method overriding.

    Example without Method Overriding

    class Vehicle{  
      void run(){System.out.println("running");}  
    }  
    
    //Child class  
    class Scooter extends Vehicle{  
         public static void main(String args[]){   
         Scooter obj = new Scooter ();  
         obj.run();  
      }  
    }  

    Output-

    running 

    Example with Method Overriding

    class Vehicle{  
      void run(){System.out.println("Running");}  
    }  
    
    //Child class  
    class Scooter extends Vehicle{  
      void run(){System.out.println("Scooter is running");}  
      
      public static void main(String args[]){  
         Scooter obj = new Scooter(); 
         obj.run();
      }
    }

    Output-

    Scooter is running

    Note-

    It is not possible to override the static method as the static method is bound with class while the instance method is bound to the object. That is why we cannot override the main method because it is also static.

    Difference between Overriding and Overloading

    Overloading

    Overriding

    It will increase the readability of the program.

    It provides the specific implementation of the method which is already provided by its super class.

    It is performed within the class.

    Method overriding is performed in two classes having IS-A (inheritance) relationship.

    parameters must be different for differentiation

    parameters must be the same to override the method

    It ensures compile time polymorphism.

    It ensures run time polymorphism.

    It can't be performed by changing the return type of the method only.

    The return type must be the same in method overriding.