Monday, February 16, 2015

overloading the main method in Java? #interview

As all of you are familiar with concept of polymorphism/overloading and overriding methods in Java. In case need more polymorphism rules refer Click here...


You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM.
For example:
public class Test1 {
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}
That will always print main(String[] args) when you run java Test1 ... from the command line, even if you specify one or two command-line arguments.
You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

No comments:

Post a Comment

Creating mirror of BST