Yes, you can overload a static method in Java. Java Method Overloading is one of the feature in OOPs concept which allows you to have two or more methods with same method name with difference in the parameters in other words, we can also call this phenomena as Compile time polymorphism.
Overloading of static method
Lets see in the below example we have a OverloadExample class which has two static disp() methods which differs in the number of parameters.
package com.javainterviewpoint; public class OverloadExample { public static void disp() { System.out.println("disp() method without parameter called"); } public static void disp(String name) { System.out.println("disp() method with parameter called : "+name); } public static void main(String args[]) { //Calling disp() method which has no parameter OverloadExample.disp(); //Calling disp() method which has one parameter OverloadExample.disp("JavaInterviewPoint"); } }
when we run the above code we will be getting the below output.
disp() method without parameter called disp() method with parameter called : JavaInterviewPoint
Overloading of methods which differs in static keyword
We cannot overload two methods which differs in static keyword but has the same method signature. When we try to do so we will be getting ” Cannot make a static reference to the non-static method “ error.
package com.javainterviewpoint; public class OverloadExample { public void disp() { System.out.println("Non static disp() method called"); } public static void disp() { System.out.println("static disp() method called121"); } public static void main(String args[]) { //Calling the disp() method OverloadExample.disp(); } }
Running the above code will lead to the below exception
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method disp() from the type OverloadExample at com.javainterviewpoint.OverloadExample.main(OverloadExample.java:21)
Ram says
good post