Explore the Concept of Overriding in Java

Method overriding happens when a subclass provides its own implementation of a method that is already defined in its superclass. It enables runtime (dynamic) polymorphism.

Rules for Method Overriding

  • The method in the subclass must have the same name, return type, and parameters as in the superclass
  • The method must be inherited, not static, final, or private
  • Access modifier in the overriding method cannot be more restrictive than the overridden method

Example

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

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

Animal a = new Dog();
a.sound(); // Output: Dog barks

Overriding vs Overloading

  • Overriding happens between a superclass and subclass; overloading happens within the same class
  • Overriding is resolved at runtime; overloading is resolved at compile time
  • Overriding requires the same method signature; overloading requires a different one
Using the @Override annotation is optional but recommended — it lets the compiler catch mistakes if the method doesn't actually override anything.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course