Sobes.tech
Junior

What is method overriding in Java?

sobes.tech AI

Answer from AI

Method Overriding is a feature in object-oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its superclass.

Key aspects:

  • Matching signature: The overridden method in the subclass must have the same signature (name, number, and types of parameters) and the same return type as in the superclass. Covariance of return type is allowed.
  • Access level: The access level of the overridden method in the subclass cannot be more restrictive than in the superclass (e.g., cannot make a public method protected). It can be widened.
  • @Override annotation: It is recommended to use the @Override annotation to indicate that a method is intended to override a superclass method. The compiler will check this.
  • Late binding: Overridden methods are invoked based on the actual object type at runtime, not the reference type.
  • Cannot override: final methods and static methods cannot be overridden. Constructors also cannot be overridden. private methods are not technically overridden but can be redefined.

Example:

// Superclass
class Animal {
    // Method to override
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

// Subclass overriding the method
class Dog extends Animal {
    @Override // Recommended annotation
    public void makeSound() {
        // Specific implementation for Dog
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        // Specific implementation for Cat
        System.out.println("Meow!");
    }
}

class Main {
    public static void main(String[] args) {
        Animal genericAnimal = new Animal();
        Animal dog = new Dog(); // Polymorphism
        Animal cat = new Cat(); // Polymorphism

        genericAnimal.makeSound(); // Output: The animal makes a sound
        dog.makeSound();         // Output: Woof! (calls Dog's method)
        cat.makeSound();         // Output: Meow! (calls Cat's method)
    }
}

Method overriding is a key mechanism for implementing polymorphism at runtime, allowing working with objects of different subclasses through a superclass reference, invoking the specialized behavior of subclasses.

What is method overriding in Java? — Java - sobes.tech