Monday, June 30, 2014

Can main method be overloaded and overridden in Java?


Can main method be overloaded and overridden in Java?

So, answers are very simple...

Overloading>>>>>>> YES

You can overload the main method. but JVM only understands public static void main(String ar[]) {,....} and looks for the main method as with given signature to start the app.

For example:

public class OverloadingMainTest{
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

      public static void main(String... args) {
System.out.println("String... args >>>> VARARGS");
}

   public static void main(Integer[] args) {
        System.out.println("main(Integer[] 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)");
    }
}


Here, i have overloaded the main method with diff. -2 types. but when you run the main method it will print:
          main(String[] args)

So, Again you can overload main method with diff.-2 signatures but it will be a simple     method only ... and it will never execute like actual main method>>

public static void main(String[] args) {
        System.out.println("main(String[] args)");
 }


Overriding>> NO

Overriding of methods can be done for only methods which belongs to an object not class, i mean to say that static methods/static variable etc. are not part of an object. and cant be overridden.

And if you try to do something like given below... you are not overriding it actually. You are hiding it. so when you run the main method of subclass JVM will not be able to load it.


public class Test{
public static void main(String[] args) {
System.out.println("Hello main");
}
}

public class Test1 extends Test{
public static void main(String[] args) {
System.out.println("Hello main test1");
}
}


And yeah if the main method which you have declared is itself not a static method then the overriding concept will be applied.


No comments:

Post a Comment

Thanks for your comments/Suggestions.