Method Overriding in Java

Advertisements

Java Method Overriding

Giving new implementaion of base class method into derived class is called method overriding. Signature of base class method and derived class must be same. Signature involves:

  • Number of arguments
  • Type of arguments
  • Sequence of arguments

Example of method or function overriding


//MethodOverridingDemo.java

    class BaseClass
    {
        void Display1()
        {
            System.out.print("\n\tThis is Display1() method of BaseClass.");
        }
        void Display2()
        {
            System.out.print("\n\tThis is Display2() method of BaseClass.");
        }
    }

    class DerivedClass extends BaseClass
    {
        void Display2()     //Overriding BaseClass method()
        {
            System.out.print("\n\tThis is Display2() method of DerivedClass.");
        }
        void Display3()
        {
            System.out.print("\n\tThis is Display3() method of DerivedClass.");
        }
    }

    class MethodOverridingDemo
    {
        public static void main(String[] args)
        {
            DerivedClass D = new DerivedClass();

            D.Display1();
            D.Display2();
            D.Display3();
        }
    }

    Output :

                This is Display1() method of BaseClass
                This is Display2() method of DerivedClass
                This is Display3() method of DerivedClass

				

In the above example DerivedClass overrides the Display2() method of BaseClass.

Advertisement