☰ See All Chapters |
Method Overloading in Java
If a class has multiple methods by same name but different parameters, it is known as Method Overloading. If we have to perform different closely related operations then having same name of methods increases the readability of the program. In Java, static polymorphism is achieved through method overloading. At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile time polymorphism or static binding.
Different ways to overload methods
By changing number of parameters of methods
By changing data type of parameters of methods
Example
package com.java4coding;
public class MethodOverloadingDemo {
public static void main(String[] args) {
System.out.println("www.java4coding.com");
} //Overloaded method public void meth(int a, int b) { System.out.println("Overloaded method"); }
//Method overloading by changing the data type of parameters public void meth(long a, int b) { System.out.println("Method overloading by changing the data type of parameters"); }
//Method overloading by changing the number of parameters public void meth(long a, int b, int c) { System.out.println("Method overloading by changing the number of parameters"); } } |
Can we do method overloading by changing the return type?
No, when we have changes in parameters between overloaded methods, when an overloaded method is called, compiler compares the arguments and parameters and method which produces the match will be called.
But when we have changes in return type there will be no option to compiler to decide the overloaded method to invoke. So method overloading is not possible by changing the return type.
All Chapters