Method Overriding in Java

Method overriding is a feature of Java that allows a subclass to provide its own implementation of a method that is already defined in its superclass. The subclass can change the behavior of the method while keeping the same method signature as the superclass. Method overriding is a type of runtime (dynamic) polymorphism, which allows a program to decide which method to call at runtime.

Here's an example of method overriding in Java:

                
    class Animal {
       public void move() {
          System.out.println("Animals can move");
       }
    }

    class Dog extends Animal {
       public void move() {
          System.out.println("Dogs can walk and run");
       }
    }

    public class TestDog {
       public static void main(String args[]) {
          Animal animal = new Animal(); // Animal reference and object
          Animal dog = new Dog(); // Animal reference but Dog object

          animal.move(); // runs the method in Animal class
          dog.move(); // runs the method in Dog class
       }
    }
                
            

In this example, we have an Animal class with a method move(). The Dog class extends the Animal class and provides its own implementation of the move() method. The TestDog class creates objects of the Animal and Dog classes and calls their move() methods.

When you call the move() method on the animal object, Java executes the implementation of the method in the Animal class, which prints "Animals can move" to the console. When you call the move() method on the dog object, Java executes the implementation of the method in the Dog class, which prints "Dogs can walk and run" to the console.

Method overriding is useful when you want to change the behavior of a method in a subclass while maintaining the same method signature as the superclass. It allows you to create more specialized classes that have their own unique behavior while still reusing the code from the superclass.