Method Overriding in Java: Definition, Rules, and Examples

Method Overriding

Method Overriding is a process in Java where a subclass provides a specific implementation for a method that is already defined in its superclass.

Key Points

1. Method Overriding requires inheritance.
2. To override a method, the subclass method must have the same name, return    type, and parameter list as the superclass method.
3. During method overriding:
  • The subclass method definition is used (exposed).
  • The superclass method definition is hidden.
  • This concept is sometimes referred to as method hiding (though strictly         speaking, method hiding is for static methods).
4. Only instance methods (non-static methods) can be overridden.
5. Method overriding cannot be achieved within the same class; it only works between subclass and superclass.

Example

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 a = new Dog();
        a.sound(); // Output: Dog barks
    }
}

Important Notes

  • Static methods cannot be overridden (they are hidden instead).
  • Method overriding is a runtime polymorphism (dynamic binding) feature in Java.
  • The @Override annotation is optional but recommended; it helps the compiler catch mistakes.

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know