0

In Java , why cant the main method be called inside the main method ? Like a recursive function.

See the following code It gives an error (Why?) : abstract class Parent { public static void main (String[] arg) { System.out.println("\n This is the Parent class"); Sub_class_1 obj1 = new Sub_class_1(); Sub_class_2 obj2 = new Sub_class_2(); obj1.message(); obj2.message(); for ( int i=1; i<=3; i++ ) { main(); /* Since main method is static , hence no object . Also , main method is in the class Parent , and we are calling main method inside the class , so only function is name is enough (no class required ). */ } } } class Sub_class_1 extends Parent { public void message() { System.out.println("\n This is first subclass"); } } class Sub_class_2 extends Parent { public void message() { System.out.println("\n This is second subclass"); } }

15th May 2017, 5:07 PM
cool_boy12344
cool_boy12344 - avatar
4 Respuestas
+ 19
You can: public class MainInMain{ public static void main(String args[]){ int randomNum = (int)(Math.random()*10); if(randomNum >= 8) System.exit(0); System.out.print("Heyhey!"); main(new String[]{"Recursion", "Gone", "Dayve"}); }} Pass the main with a String...so as it is done ;) P.S. You can apply this to your code as well!
15th May 2017, 5:20 PM
Dev
Dev - avatar
+ 19
There's another way called NestedInner: class Outer { static class NestedInner { public static void main(String[] args) { System.out.println("Inside the main"); }//inner main }//NestedInner public static void main(String[] args) { NestedInner.main(new String[1] );//**calling of Main method** System.out.println("Hello World!"); }//outer main }//Outer
15th May 2017, 5:23 PM
Dev
Dev - avatar
+ 4
You couldn't because main() was not a method. The signature does not match anything. You need to pass an array of type string as the arguments. Ex/ main(arg); main is just a method, it works like any others.
15th May 2017, 5:57 PM
Rrestoring faith
Rrestoring faith - avatar