«Back to Home

Core Java

Topics

Method Overriding In Java

Method Overriding

In Java, method overriding means to override the method of an existing method. With the use of method overriding, we can create two methods with same name.
 
If child class provides the specific implementation of the method, which is already provided by its parent class. It is called as a method overriding.

Advantage of Method Overriding
  • It is used to achieve runtime polymorphism.

  • It is used to provide specific implementation of a method through child class, which is already provided by its super class.
Let’s see an example, given below.
 
Code
  1. class Car {  
  2.     int speed = 90;  
  3.     void run() {  
  4.         System.out.println("Car is running fast");  
  5.     }  
  6. }  
  7. public class Swift extends Car {  
  8.     int speed = 60;  
  9.     void run() {  
  10.         System.out.println("Swift is running smoothly");  
  11.     }  
  12.     public static void main(String args[]) {  
  13.         Swift s = new Swift();  
  14.         System.out.println("Speed of swift car:" + s.speed);  
  15.         s.run();  
  16.     }  
  17. }  
11

Output

12

In the example, mentioned above, we defined the run method in the subclass, which is already defined in its parent class also but subclass has some specific implementation. There is IS-A relationship (inheritance) between the classes. Both classes have same method name and parameter. Hence, there is a method overriding.
 
Rules of Method Overriding in Java
  1. Method argument list must be same name as the parent class.

  2. Must have IS-A relationship.

  3. Return type must be same.

  4. Access level cannot be more restrictive than the overridden method’s access level and super class method, which is not declared private.

  5. Final method cannot be overridden.

  6. Static method cannot be overridden but can be re-declared.

  7. Constructor cannot be overridden.
In Java, we cannot override static method because static method is bound with class and instance method, which is bound with the object. Their memories are also different. Static belongs to class area and instance belongs to heap area.
 
We cannot override Java main method also because main method is static method.
 
Summary

Thus, we learnt that method overriding means to override the method of an existing method in Java and also learnt how we can override the method.