0 votes
in JAVA by
Comment on method overloading and overriding by citing relevant examples.

1 Answer

0 votes
by
In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

Only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

class OverloadingHelp {

    public int findarea (int l, int b) {

            int var1;

            var1 = l * b;

            return var1;

    }

    public int findarea (int l, int b, int h) {

            int var2;

            var2 = l * b * h;

            return var2;

    }

}

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding.

Let’s give a look at this example:

class HumanBeing {

        public int walk (int distance, int time) {

                int speed = distance / time;

                return speed;

        }

}

class Athlete extends HumanBeing {

        public int walk(int distance, int time) {

                int speed = distance / time;

                speed = speed * 2;

                return speed;

        }

}

Both class methods have the name walk and the same parameters, distance and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

Related questions

0 votes
asked May 6, 2020 in C Sharp by SakshiSharma
0 votes
asked Jun 16, 2019 in JAVA by reins.robin
...