Can we Overload static method in Java? Program - Example (original) (raw)
Overloading static method In Java
Yes, we can overload the static method in Java. In terms of method overloading, the static method is just like normal methods. To overload the static method, you need to provide another static method with the same name but a different method signature. The static overloaded method is resolved using Static Binding during compile time. The overloading method in Java is completely different than the overriding method. As discussed in the last article, we can not override the static method in Java, but we can certainly overload a static method in Java. Here is an example that confirms that we can overload static method in Java:
Overloading Static method in Java - example
In this example, we have a static method called greet(String name) which takes a string argument as a name and print a default greeting message as "Hello John".
Now to show that we can overload the static method in Java, I have provided another static method with the same name but a different method signature takes the name of a person to greet and greeting a message like Good Morning, Good Evening, etc.
Here is our complete Java program to demonstrate that static method can be overloaded in Java:
/**
* Java program to show that we can overload static method in Java.
*/
public classStaticOverloadingTest {
public static voidmain(String args[]) {
greet("John"); //will call a static method with one String argument
greet("John," "Good Morning"); //overloaded static method will be call
}
/*
* static method which will be overloaded
*/
public static voidgreet(String name){
System.out.println("Hello " + name);
}
/*
* Another static method that overloads above Hello method
* This shows that we can overload static method in Java
*/
public static voidgreet(String name, Stringgreeting){
System.out.println(greeting + " " + name);
}
}
Output
Hello John
Good Morning John
That's all on How can we overload static methods in Java. In summary, Don't confuse between method overloading and method overriding. In short, you can overload the static method in Java, but you can not override the static method in Java.
Other Java OOP tutorials from JDK67
- What is method overloading in Java
- What is method overriding in java
- Top 10 Java coding interview question
- What is the difference between String and StringBuffer in Java
- Can we override the private method in Java
Thanks for reading this article so far. If you like an object-oriented programming tutorial, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.