Join Regular Classroom : Visit ClassroomTech

Method overriding in java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

Usage of Java Method Overriding

  • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  • Method overriding is used for runtime polymorphism

Rules of method overriding:

  • Same method name
  • Different class
    • No. of arg
    • Type of arg
    • Seq of arg
  • Inheritance(IS-A relationship)

Example of method overriding

/* JAVA program to understand Method overriding  */
/* www.codewindow.in */
import java.util.*;
class dog
{
    public void run()
    {
        System.out.println("Dog is running");
        
    }
}
class cat extends dog
{
    public void run()
    {
        System.out.println("Cat is running");
        
    }
}
public class codewindow
{
    public static void main(String args[])
    {
        cat ob=new cat();
        ob.run();
        
    }
}

Output

Cat is running.