0
0
Javaprogramming~5 mins

Method overriding rules in Java

Choose your learning style9 modes available
Introduction

Method overriding lets a child class change how a method from its parent works. This helps make programs flexible and easy to update.

When you want a child class to do something different from the parent class for the same action.
When you need to customize behavior in a subclass without changing the parent class code.
When using polymorphism to call child class methods through parent class references.
When you want to extend or improve a method's behavior in a subclass.
When implementing abstract methods from a parent or interface.
Syntax
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.

Examples
Child class Dog changes the sound method to print a dog-specific message.
Java
class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}
The Car class overrides speed to return a different number.
Java
class Vehicle {
    int speed() {
        return 50;
    }
}

class Car extends Vehicle {
    @Override
    int speed() {
        return 100;
    }
}
Sample Program

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.

Java
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();
    }
}
OutputSuccess
Important Notes

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.

Summary

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.