Explain method overloading and method overriding with example.


Q.) Explain method overloading and method overriding with example.

Subject: Object Oriented Programming and Methodology

Method Overloading

Method overloading is a feature that allows a class to have multiple methods with the same name but different parameters. This allows you to write code that is more concise and easier to read.

For example, the following Java class has two methods called add():

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

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

The first add() method takes two integers as parameters and returns their sum. The second add() method takes two doubles as parameters and returns their sum.

You can use either of these methods by calling them with the appropriate parameters. For example, the following code calls the first add() method to add two integers:

MyClass myClass = new MyClass();
int result = myClass.add(1, 2);

The following code calls the second add() method to add two doubles:

MyClass myClass = new MyClass();
double result = myClass.add(1.5, 2.5);

Method Overriding

Method overriding is a feature that allows a subclass to define a new implementation of a method that is already defined in a superclass. This allows you to create subclasses that have specialized behavior.

For example, the following Java class defines a method called draw():

public class Shape {
  public void draw() {
    System.out.println("Drawing a shape");
  }
}

The following Java class extends the Shape class and overrides the draw() method:

public class Circle extends Shape {
  @Override
  public void draw() {
    System.out.println("Drawing a circle");
  }
}

When you create a Circle object and call the draw() method, the overridden method in the Circle class will be called instead of the method in the Shape class.

Circle circle = new Circle();
circle.draw(); // Prints "Drawing a circle"

Example

The following Java code demonstrates method overloading and method overriding:

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

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

public class MySubclass extends MyClass {
  @Override
  public int add(int a, int b) {
    return a + b + 1;
  }
}

public class Main {
  public static void main(String[] args) {
    MyClass myClass = new MyClass();
    int result = myClass.add(1, 2);
    System.out.println(result); // Prints "3"

    MySubclass mySubclass = new MySubclass();
    result = mySubclass.add(1, 2);
    System.out.println(result); // Prints "4"

    double result2 = myClass.add(1.5, 2.5);
    System.out.println(result2); // Prints "4.0"
  }
}

Output:

3
4
4.0