Method overloading
and method overriding
in Java
Method Overloading Method Overriding
Method overloading is a compile-time Method overriding is a run-time
polymorphism. polymorphism.
Method overriding is used to grant the
Method overloading helps to increase specific implementation of the method
the readability of the program. which is already provided by its parent
class or superclass.
It occurs within the class. It is performed in two classes with
inheritance relationships.
Method overloading may or may not Method overriding always needs
require inheritance. inheritance.
In method overloading, the return type In method overriding, the return type
can or can not be the same, but we just must be the same or co-variant.
have to change the parameter.
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
The argument list should be different The argument list should be the same in
while doing method overloading. method overriding.
• class MethodOverloadingEx {
• static int add(int a, int b) { return a + b; }
• static int add(int a, int b, int c)
• {
• return a + b + c;
• }
• // Main Function
• public static void main(String args[])
• {
• System.out.println("add with 2 parameters");
• // Calling function with 2 parameters
• System.out.println(add(4, 6));
• System.out.println("add with 3 parameters");
• // Calling function with 3 Parameters
• System.out.println(add(4, 6, 7));
• }
• }
• // Method overriding Base Class
• class Animal {
• void eat() {
• System.out.println("eat() method of base class");
• System.out.println("Animal is eating.");
• }
• }
• // Derived Class
• class Dog extends Animal {
• @Override
• void eat() {
• System.out.println("eat() method of derived class");
• System.out.println("Dog is eating.");
• }
• // Method to call the base class method
• void eatAsAnimal() {
• super.eat();
• }
•}
• // Driver Class
• class MethodOverridingEx {
• // Main Function
• public static void main(String args[]) {
• Dog d1 = new Dog();
• Animal a1 = new Animal();
• // Calls the eat() method of Dog class
• d1.eat();
• // Calls the eat() method of Animal class
• a1.eat();
• // Polymorphism: Animal reference pointing to Dog object
• Animal animal = new Dog();
• // Calls the eat() method of Dog class
• animal.eat();
• // Polymorphism: Animal reference pointing to Dog object
• Animal animal = new Dog(); //
•
• // Calls the eat() method of Dog class
• animal.eat();
•
• // To call the base class method, you need to use a Dog reference
• ((Dog) animal).eatAsAnimal();
• }
•}
OUTPUT
• eat() method of derived class
• Dog is eating.
• eat() method of base class
• Animal is eating.
• eat() method of derived class
• Dog is eating.
• eat() method of base class
• Animal is eating.