Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a main() method of class be invoked from another class in java

Tags:

java

Can a main() method of class be invoked in another class in java?

e.g.

class class1{    public static void main(String []args){    }  }  class class2{    public static void main(String []args){       class1.main();   }  } 
like image 407
sa. Avatar asked Mar 31 '10 03:03

sa.


People also ask

How do you call a main method from another method in Java?

Call a MethodInside main , call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"

Does main method belong to any class?

Yes. Every method or field must belong to a class (or interface/enum).

Can two classes have main methods in Java?

From the above program, we can say that Java can have multiple main methods but with the concept of overloading. There should be only one main method with parameter as string[ ] arg.


2 Answers

If you want to call the main method of another class you can do it this way assuming I understand the question.

public class MyClass {      public static void main(String[] args) {          System.out.println("main() method of MyClass");         OtherClass obj = new OtherClass();     } }  class OtherClass {      public OtherClass() {          // Call the main() method of MyClass         String[] arguments = new String[] {"123"};         MyClass.main(arguments);     } }  
like image 75
Binary Nerd Avatar answered Sep 17 '22 19:09

Binary Nerd


if I got your question correct...

main() method is defined in the class below...

public class ToBeCalledClass{     public static void main (String args[ ]) {       System.out.println("I am being called");    } } 

you want to call this main method in another class.

public class CallClass{      public void call(){        ToBeCalledClass.main(null);     } } 
like image 28
Kamran Siddiqui Avatar answered Sep 19 '22 19:09

Kamran Siddiqui