The method overloading vs overriding in Java

Beknazar
3 min readMay 19, 2021
  1. Method Overloading
  2. Method Overriding

Method Overloading

  1. Method overloading is when more than one method with the same name but a different number or type of arguments defined in the same class.
  2. The return type of the method can be different.
public class CalculatorUtil {   public static int sum(int i, int i2) {
return i + i2;
}
public static int sum(int i, int i2, int i3) {
return i + i2 + i3;
}

public static double sum(double i, double i2) {
return i + i2;
}

public static double sum(double i, double i2, double i3) {
return i + i2 + i3;
}
}

In the above example, we have four overloaded methods. It’s convenient because when the client code will use our sum they won't think should we pass int or double.

One of the most popular method

System.out.println();

has 10 overloaded methods

Did you know about that?

It is super useful for us. When we use it we just know it will print output in the console and we can pass everything we wanted to print.

Method Overriding

Method overriding when a child or concrete class overrides its parent method. We can override our parent class methods when we extend them and we can override methods of interfaces when we implement them(we implement abstract methods by overriding them).

Rules of overriding:

  1. Method name and number, order, and type of arguments should be exactly the same as the parent’s method.
  2. Return type should be the same or covariant with the parent method.
  3. The access modifier should be the same or more visible than the parent method.
  4. If an exception declaration exists in the parent method, the child method can have the same type of exception declaration or a smaller type.

That’s all I have for today. Have a nice day!

--

--