Method overloading and overriding in java

Overriding:

  • Method overriding is a mechanism in which a subclass inherits the methods of super class and sometimes the subclass modifies the implementation of a method defined in super class.
  • That means if subclass (Derived class) has the same method as declared in the parent class (base class).
  • Method overriding is used for runtime polymorphism.

Rules for Java Method Overriding:

  • The method must have the same name as in the parent class
  • The method must have the same parameter as in the parent class.
  • There must be inherited.
  • A static method cannot be overridden. It can be proved by runtime polymorphism.

Syntax:

  1. class base_class_name

    {

    return_type method_name(parameter_list)

    {

              //Statement

    }

    }

     

    class derived_class_name

    {

    base_class_method(parameter_list)

    {

              //Statement

    }

    }

Example program:

  1. class Bank {

        int get_Rate_Of_Interest() {

            return 0;

        }

    }

    class SBI extends Bank {

        int get_Rate_Of_Interest() {

            return 8;

        }

    }

    class ICICI extends Bank {

        int get_Rate_Of_Interest() {

            return 7;

        }

    }

    class AXIS extends Bank {

        int get_Rate_Of_Interest() {

            return 9;

        }

    }

    class Method_Overriding {

        public static void main(String args[]) {

            SBI s = new SBI();

            ICICI i = new ICICI();

            AXIS a = new AXIS();

            System.out.println("SBI Rate of Interest: " + s.get_Rate_Of_Interest());

            System.out.println("ICICI Rate of Interest: " + i.get_Rate_Of_Interest());

            System.out.println("AXIS Rate of Interest: " + a.get_Rate_Of_Interest());

        }

    }

Output:

Method overloading:

  • Overloading is a mechanism in which we can use many methods having the same function name but can pass different number of parameters or different types of parameters.

Syntax:

  1. class base_class_name

    {

    return_type method_name(parameter_list)

    {

              //Statement

    }

    return_type same_method_name(parameter_list)

    {

              //Statement

    }

    }

Example program:

  1. class SimpleCalculator

    {

        int add(int a, int b)

        {

             return a+b;

        }

        int  add(int a, int b, int c) 

        {

             return a+b+c;

        }

    }

    class Method_Overloading {

       public static void main(String args[])

       {

           SimpleCalculator obj = new SimpleCalculator();

           System.out.println("Adding two number : "+obj.add(10, 20));

           System.out.println("Adding three number : "+obj.add(10, 20, 30));

       }

    }

Output:
Share:

No comments:

Post a Comment

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me