Method Overriding in Java

Profile picture for user arilio666

Method overriding is a concept in Java where a subclass provides a method already defined in its superclass. This allows the subclass to customize the behavior of the method inherited from the superclass according to its own needs. Simply put, the child can use the parent's method with the same name and override it to the child's need.

Instructions To Use Method Overriding:

  • To override a subclass method, the method in the subclass must have the same name, return type, and parameter list.
  • Using the @Override annotation when overriding a method in Java is a good practice. This annotation indicates that the method is intended to override a method in the superclass, and the compiler will generate an error if the overriding method does not override any method in the superclass.
  • Method overriding is applicable only in an inheritance hierarchy, where a subclass inherits from a superclass. 
  • Suppose a subclass overrides a method also present in its superclass, and the subclass wants to invoke the overridden method from within its implementation. In that case, it can use the super keyword followed by the method name to refer to the overridden method in the superclass.
  • Method overriding is an example of polymorphism in Java, where a subclass object can be treated as an object of its superclass. 
     

Example:

class Shinobi {
   void villageNative() {
       System.out.println("Leaf");
   }
}
class Naruto extends Shinobi {
   @Override
   void villageNative() {
       System.out.println("Uzumaki In Leaf Village");
   }
}
public class Main {
   public static void main(String[] args) {
       Shinobi shinobi = new Shinobi();
       Shinobi nar = new Naruto();
       shinobi.villageNative(); // Output: Leaf
       nar.villageNative(); // Output: Uzumaki In Leaf Village
   }
}
  • Here Shinobi is the parent class extended by the child Naruto class and uses the same method villageNative overridden and printed each of the class's methods with the respective object.
Tags