DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-65 Method Overriding in Java (Runtime Polymorphism)

What is Method Overriding?

Method overriding happens when:

  • A child class provides its own implementation of a method that is already defined in its parent class.
  • Both methods should have the same name and same number of arguments.

Key Points

  • Method overriding always involves two different classes – a parent class and a child class.
  • It is resolved at runtime, hence called runtime polymorphism.
  • When we create an object memory, if the child class has overridden a method, then first priority is given to the child class method.
  • We use the super keyword to refer to the parent class object or to call the parent class method when needed.
  • The method is called based on the object created. For example, if a child object is created, the overridden method in the child class will be executed.
  • Access Modifiers Rule: In method overriding, we cannot reduce the access level of the overridden method in the child class. For example, if the parent method is public, the child method cannot be protected or private.

Example

public class Parents {
    int age = 48;

    void fixMarriage() {
        System.out.println("for their child, parent opinion");
    }
}

public class Children extends Parents {
    int age = 28;

    public static void main(String[] args) {
        // same method name, same no. of args, in two diff classes (parent-child) - method overriding or runtime polymorphism
        Children ch = new Children();
        ch.fixMarriage();
        ch.printAge();
    }

    public void printAge() {
        System.out.println(this.age);   // this refers to current object
        System.out.println(super.age);  // super refers to super class object (parent class)
    }

    public void fixMarriage() {  // we cannot reduce access in method overriding
        super.fixMarriage();
        System.out.println("child - opinion");  // first priority is child method
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)