Friday, August 31, 2012

Can we overload static method in Java Program - Example

Overloading static method In Java
Yes, we can overload static method in Java. In terms of method overloading static method are just like normal methods and in order to overload static method you need to provide another static method with same name but different method signature. Static overloaded method are resolved using Static Binding during compile time. Overloading method in Java is completely different than overriding method and as discussed in our last article we can not override static method in Java but we can certainly overload static method in Java. Here is an example which confirms that we can overload static method in Java:

 

Overloading Static method in Java - example

Can we overload static method in Java with ExampleIn this example we have a static method called greet(String name) which takes a String argument as name and print a default greeting message as "Hello John". Now to show that we can overload static method in Java I have provided another static method with same name but different method signature which not only takes name of person to greet but also greeting message e.g. Good Morning, Good Evening etc.

/**   
 * Java program to show that we can overload static method in Java.
 */

public class StaticOverloadingTest {
 
    public static void main(String args[]) {
        greet("John"); //will call static method with one String argument
        greet("John", "Good Morning"); //overloaded static method will be call    

    }
 
    /*
     * static method which will be overloaded
     */

    public static void greet(String name){
        System.out.println("Hello " + name);
    }
 
    /*
     * Another static method which overload above Hello method
     * This shows that we can overload static method in Java
     */

    public static void greet(String name, String greeting){
        System.out.println(greeting + " " + name);
    }


}
Output
Hello John
Good Morning John


That's all on How can we overload static method in Java. In summary, Don't confuse between method overloading and method overriding. In short, you can overload static method in Java but you can not override static method in Java.

Other Java OOPS tutorial from JDK67

3 comments:

  1. ofcourse you can not overload static method, but you can hide them in Java.

    ReplyDelete
    Replies
    1. you can overload but not override static methods

      Delete
  2. I am new to java. Your blog is really good. It helps me in learning java. Keep writing more articles.

    ReplyDelete

Java67 Headline Animator