method overriding in Java

method overriding in Java

Method overriding in Java allows a subclass to provide a specific implementation of a method already defined in its superclass. When a subclass method has the same name, return type, and parameters as a method in the superclass, it overrides the superclass method.

method overriding in Java

Key Points:

  • Same Signature: The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
  • Inheritance: Method overriding occurs in the context of inheritance.
  • @Override Annotation: Indicates that a method is intended to override a method in the superclass.
  • Access Modifiers: The overriding method cannot have a more restrictive access level than the overridden method.
  • Exceptions: The overriding method can throw unchecked exceptions but not new or broader checked exceptions.

Example

Consider a superclass ‘Animal’ and a subclass Dog.

Syntax
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();  // Animal reference and object
        Animal myDog = new Dog();  // Animal reference but Dog object
        
        myAnimal.sound();  // Calls Animal's sound()
        myDog.sound();  // Calls Dog's sound()
    }
}

Benefits:

  • Polymorphism: Enables runtime polymorphism, allowing method calls to resolve to the most specific implementation.
  • Dynamic Method Dispatch: Allows a class to specify behavior specific to its type.
  • Code Reusability: Facilitates code reuse and maintains readability and maintainability.

Method overriding is essential for implementing runtime polymorphism in Java, providing flexibility and enabling more dynamic applications.