Method overriding lets a child class change how a method from its parent works. This helps make programs flexible and easy to update.
Method overriding rules in Java
class Parent { void show() { System.out.println("Parent show method"); } } class Child extends Parent { @Override void show() { System.out.println("Child show method"); } }
The method in the child class must have the same name, return type, and parameters as the parent method.
Use the @Override annotation to help the compiler check you are correctly overriding.
Dog changes the sound method to print a dog-specific message.class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } }
Car class overrides speed to return a different number.class Vehicle { int speed() { return 50; } } class Car extends Vehicle { @Override int speed() { return 100; } }
This program shows method overriding. The greet method is called on parent, child, and parent reference to child object. The child method runs when the object is child.
class Parent { void greet() { System.out.println("Hello from Parent"); } } class Child extends Parent { @Override void greet() { System.out.println("Hello from Child"); } } public class Main { public static void main(String[] args) { Parent p = new Parent(); p.greet(); Child c = new Child(); c.greet(); Parent pc = new Child(); pc.greet(); } }
The overriding method cannot have more restrictive access than the parent method. For example, if parent method is public, child method must be public too.
Static methods cannot be overridden, only instance methods can.
Constructors cannot be overridden.
Method overriding lets a child class provide its own version of a parent method.
The method signature must match exactly.
Use @Override to avoid mistakes.