Monday, January 4, 2021

What is Method Overloading in Java? An Example

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Method Overloading

What is method overloading in Java?

Method overloading in Java is an object-oriented programming concept that allows a programmer to declare two methods of the same name but with different method signatures, like change in the argument list or change in the type of argument. Method overloading is a powerful Java programming technique to declare a method that does a similar job but with a different kind of input. One of the most popular examples of method overloading is the System.out.println() method whose job is to print data on the console. This method is overloaded to accept all kinds of data types in Java. 

You have the println() method which takes String, int, float, double, or even char in output. All of those methods are collectively referred to as an overloaded method in Java.

You should also know that difference between method overloading and overriding is also a popular Java interview question. In the next section, we will some important points about method overloading in Java and then a simple example of how to overload a method in Java.

Properties of method overloading in Java

1) Overloaded methods are bonded using static binding in Java. Which occurs during compile time i.e. when you compile a Java program. During the compilation process, the compiler bind method calls to the actual method.

2) Overloaded methods are fast because they are bonded during compile time and no check or binding is required during runtime.

3) Most important rule of method overloading in Java is that two overloaded methods must have a different signature. 

Here is an example of what does method signature means in Java:

◉ A number of arguments to a method are part of the method signature.

◉ Type of argument to a method is also part of the method signature

◉ Order of argument also forms part of the method signature provided they are of a different type.

◉ The return type of method is not part of the method signature in Java.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Method Overloading

Method Overloading Example in Java


Here is a list of method and there a corresponding overloaded method with the reason that How they are overloaded :

Original method :

public void  show(String message){
      System.out.println(message);
}

Overloaded method: number of argument is different

public void  show(String message, boolean show){
      System.out.println(message);
}

Overloaded method: type of argument is different

public void  show(Integer message){
      System.out.println(message);
}

Not an Overloaded method: the only return type is different

public boolean show(String message){
      System.out.println(message);
      return false;
}

Related Posts

0 comments:

Post a Comment