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(); } }
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!"
Yes. Every method or field must belong to a class (or interface/enum).
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.
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); } }
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With