Method Overloading in Java

Method overloading in Java occurs when two or more methods in a class have the same name and a different list of parameters. In order for a method to be called for execution, its name must be known, as well as the number, order, and types of its parameters. This part of the method is called the signature. 

For example, the method:

public int sum(int a, int b, int c) {  
        // body of the method  
} 

has a signature:

sum(int a, int b, int c)

Overloaded Methods in Java

Methods with the same name and different parameters are called overloaded methods.

Example

class Printer {

  // fields

  public void printBook(String bookName) {
    // ...
  }

  public void printBook(String bookName, int numberOfPages) {
    // ...
  }
}

You can see that we have two versions of the method printBook. The signature of the two methods in the class must be different so that the Java compiler can determine which method to call.  This is easily determined based on the number, order, and types of arguments listed in the method call. 

Return Type in the Method Overloading

Let’s see what happens if we have two methods with the same signature, but with different return types:

class Printer {

  // fields

  public void printBook(String bookName) {
    // ...
  }

  public String printBook(String bookName) { // DOES NOT COMPILE
    return bookName;
  }
}


This will not compile since the return type does not affect the method overloading. It is not part of the signature, and we already said the signature of the methods must be different.

Another Example of the Method Overloading

class Car {
  
  public void startEngine() {
    System.out.println("Engine is started...");
  }

  public void startEngine(int num) {
    System.out.println("Engine with number: " + num + " is started...");
  }

  public String startEngine(String brand) {
    System.out.println("Engine with brand: " + brand + " is started...");
    return brand;
  }

  public int startEngine(int engineNumber) { // DOES NOT COMPILE
    System.out.println("Engine with number: " + engineNumber + " is started...");
    return engineNumber;
  }

}


The last method declaration won’t compile because we have already declared the method with the same name that accepts the parameter of type int.

That was all about method overloading in Java. Read the following tutorial to learn about Method Overriding

Happy Learning!

 

Leave a Reply

Your email address will not be published.