DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Method Overriding in Java:

What is Method Overriding?

  • Declaring a method in sub/child class which is already present in parent class is known as method overriding.

  • In this case the method in parent class is called overridden method and the method in child class is called overriding method.

  • method overriding is a run-time polymorphism.

    +----------------+
    |    Animal      |
    |  sound()       |
    +----------------+
             ▲
             |
    +----------------+
    |      Dog       |
    |  sound()       |  
    +----------------+
    

Example :

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

}

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

}

public class Main {

    public static void main(String[] args)
    {
        Dog dg = new Dog();
        dg.sound();
    }
}

Output :
Dog barks
Enter fullscreen mode Exit fullscreen mode

What are the rules for method overriding?

Method name must be the same & Parameters must be the same:

  • The overriding method in the subclass must have the exact same name, number and type of parameters.

Must have IS-A relationship (inheritance) :

  • Method overriding requires an "is-a" relationship, meaning the subclass must inherit from the superclass.

Access Modifier :

  • Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class.

Methods that can't be inherited :

  • final Methods: Methods declared as final cannot be overridden, as they are meant to have the final implementation. static Methods: Methods declared as static cannot be overridden; if a subclass declares a static method with the same signature, it is called "method hiding," not overriding.
  • private Methods: private methods are not inherited by subclasses and thus cannot be overridden.
  • Constructors: Constructors cannot be overridden.
  • static Methods: Methods declared as static cannot be overridden; if a subclass declares a static method with the same signature, it is called "method hiding," not overriding.

Same Return Type :

  • The child class method can have exactly the same return type as the parent method.

What is override annotation?

  • It is an annotation in Java that tells the compiler that this method is overriding a method from the parent class.

Top comments (0)