DEV Community

Divya Divya
Divya Divya

Posted on

Method Overriding in Java

When a subclass provides a specific implementation for a method that is already defined in its parent class, it is called method overriding. The overridden method in the subclass must have the same name, parameters, and return type as the method in the parent class.

Rules for Method Overriding

  • Name, parameters, and return type must match the parent method.
  • Java picks which method to run at run time, based on the actual object type, not just the reference variable type.
  • Static methods cannot be overridden.

Usage of Java Method Overriding

  • Method overriding is used for achieving run-time polymorphism.
  • Method overriding is used for writing specific definition of a subclass method (this method is known as the overridden method).
class Animal {

    void move(){
        System.out.println(
      "Animal is moving."); 

    }
    void eat(){

        System.out.println(
      "Animal is eating."); 

    }
}

class Dog extends Animal{

    @Override void move(){ 

      // move method from Base class is overriden in this
      // method
        System.out.println("Dog is running.");
    }
    void bark(){

        System.out.println("Dog is barking."); 

    }
}

public class Geeks {
    public static void main(String[] args)
    {
        Dog d = new Dog();
        d.move(); 
        d.eat(); 
        d.bark();
    }
}
Enter fullscreen mode Exit fullscreen mode

To be discused
Output

Top comments (0)