Can we overload static method in java

I have assumed you are familiar with method overloading. If you are not, then read the method overloading first.
The method Overloading is a feature of Java language that allows different method can have the same name, but different signatures, especially the number of input parameters and type of input parameters. Many developers have asked one question that is “Can the static method be overload in Java?”  
In this article, we will discuss how to overload static methods.

method overloading in java?
Method overloading in Java means multiple methods having the same name but different in parameters. A class can hold several methods having the same name, but different types/order/number of parameters.
There are three ways to overload the methods you can read them in detail. Here is the link of a separate post.
1. You can overload by changing the number of arguments/parameters.
2. You can overload by changing the data type of arguments.
3. The Order of the parameters of methods.

“Can the static method be overload in Java?”  

can we overload static method in java

Yes, we can overload the static method. A class can have more than one static method with the same name, but different in input parameters. You can overload the static method by changing the number of arguments or by changing the type of arguments. There are many ways to overload a method in Java you can read them from here: Ways to overload the methods?

Example:

public class MethodOverloadingOfStaticMethod 
{
	public static void show(String name)
	{
		System.out.println("Name of person = "+name);
	}
	
	public static void show(int age)
	{
		System.out.println("Person age is = "+ age);
	}
	public static void main (String [] args) 
	{
		// If user providing parameter of String type then first method called
		MethodOverloadingOfStaticMethod.show("Ram");
		// If user providing parameter of int type then second method called
		MethodOverloadingOfStaticMethod.show(18);
	}
}

Output: Name of person = Ram
Person age is = 18

Can we overload methods that differ only by static keyword?

No, we can’t overload the method if they differ only by static keyword. If we are defining two methods with the same name and parameters but we are differentiating them by static keyword. Then compiler with show error “Duplicate method printData() in type MainClass”.

public class MainClass 
{
	public void printData()
	{
		System.out.println("Print data method without static keyword");
	}
	
	public static void printData()
	{
		System.out.println("Print data method without static keyword");
	}
	
	public static void main(String arg[])
	{
		// Body of main method
	}
}

Leave a Comment