Sunday, January 5, 2014

Can I call main() from another class?

Can I call main() from another class? Simple answer is “YES”. Here is a simple example.

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

Now, we would like to call main() method of SimpleStarter class from another class. As main() is a static method, we can call main by using class name.
public class MainCallerClass {
    public static void main(String[] args) {
        System.out.println("Main of MainCallerClass");
        SimpleStarter.main(args);
    }   
}

When we execute MainCallerClass, here is what we see as output :

Main of MainCallerClass
Main of SimpleStarter class

Posted  by Nancy
@10:12 pm 01/05/2013




1 comment: