Explain method overloading and method overriding with suitable example. Also give their necessary conditions.


Q.) Explain method overloading and method overriding with suitable example. Also give their necessary conditions.

Subject: object oriented programming

Method Overloading

Method overloading in Java is a feature that allows a class to have multiple methods of the same name, but with different parameters. This allows you to write code that is more flexible and easier to read. For example, you could have a method called add() that takes two integers as parameters, and another method called add() that takes a String and an integer as parameters. The compiler will automatically determine which method to call based on the arguments that you pass to it.

Necessary conditions for method overloading:

  • The methods must have the same name.
  • The methods must have different parameters.
  • The methods must be defined in the same class.
  • The return type of the methods does not matter.

Example:

class Calculator {

    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, int b) {
        return a + b;
    }

    public String add(String a, int b) {
        return a + String.valueOf(b);
    }
}

public class Main {

    public static void main(String[] args) {
        Calculator calculator = new Calculator();

        int result1 = calculator.add(1, 2);
        double result2 = calculator.add(3.5, 4);
        String result3 = calculator.add("Hello", 5);

        System.out.println(result1); // Output: 3
        System.out.println(result2); // Output: 7.5
        System.out.println(result3); // Output: Hello5
    }
}

Method Overriding

Method overriding in Java is a feature that allows a subclass to provide its own implementation of a method that is already defined in its superclass. This allows you to create new classes that inherit the behavior of existing classes, while also customizing that behavior as needed. For example, you could create a subclass of the Animal class that overrides the speak() method to make the animal produce a different sound.

Necessary conditions for method overriding:

  • The methods must have the same name.
  • The methods must have the same parameters.
  • The methods must have the same return type.
  • The overriding method must be defined in a subclass of the class that defines the overridden method.
  • The overriding method must not be declared final.

Example:

class Animal {

    public void speak() {
        System.out.println("Animal speaks");
    }
}

class Dog extends Animal {

    @Override
    public void speak() {
        System.out.println("Dog barks");
    }
}

public class Main {

    public static void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = new Dog();

        animal.speak(); // Output: Animal speaks
        dog.speak(); // Output: Dog barks
    }
}