En Java, ¿podemos llamar al método main() de una clase desde otra clase?

En Java, ¿podemos llamar al método main() de una clase desde otra clase?  

¿Cómo llamar al método ‘public static void main(String[] args)’ desde nuestro código?
Estas son algunas preguntas que generalmente desconciertan a un programador de Java. Este artículo pretende dar respuesta a estos problemas de una forma sencilla y eficaz.
Como sabemos, el método main() para cualquier aplicación Java como entorno de tiempo de ejecución de Java llama primero al método main(). Entonces, es obvio que no necesitamos llamar al método main() por nosotros mismos, ya que ya se llama cuando se inicia el programa. Pero, ¿qué pasa si queremos llamar al método main() desde algún lugar de nuestro programa? Ese es el problema.
Solución:
Aunque Java no prefiere que se llame al método main() desde otro lugar del programa, no prohíbe que uno lo haga también. Entonces, de hecho, podemos llamar al método main() cuando y donde lo necesitemos. 
Pero llamar al método main() desde nuestro código es complicado. Puede conducir a muchos errores y excepciones , tales como:
 

  • El método main() debe llamarse desde un método estático solo dentro de la misma clase.

Java

// Java method to show that the main() method
// must be called from a static method only
// inside the same class
 
import java.io.*;
 
class GFG {
 
    // The method that calls the main() method
    // Note that this method is not static
    void mainCaller()
    {
        System.out.println("mainCaller!");
 
        // Calling the main() method
        main(null);
    }
 
    // main() method
    public static void main(String[] args)
    {
        System.out.println("main");
 
        // Calling the mainCaller() method
        // so that main() method is called externally
        mainCaller();
    }
}
  • Error de compilación en código java:
prog.java:27: error: non-static method mainCaller()
                     cannot be referenced
                     from a static context
        mainCaller();
        ^
1 error
  • Al método main() se le deben pasar los argumentos String[] al llamarlo desde otro lugar.

Java

// Java method to show that the main() method
// must be passed the String[] args
// while calling it from somewhere else
 
import java.io.*;
 
class GFG {
 
    // The method that calls the main() method
    static void mainCaller()
    {
        System.out.println("mainCaller!");
 
        // Calling the main() method
        // Note that no parameter is passed
        main();
    }
 
    // main() method
    public static void main(String[] args)
    {
        System.out.println("main");
 
        // Calling the mainCaller() method
        // so that main() method is called externally
        mainCaller();
    }
}
  • Error de compilación en código java:
prog.java:17: error: method main in class GFG
                     cannot be applied to given types;
        main();
        ^
  required: String[]
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error
  • Llamar al método main() conducirá a un bucle infinito ya que la pila de memoria sabe que debe ejecutar solo el método main().

Java

// Java method to show that Calling the main() method
// will lead to an infinite loop as the memory stack
// knows to run only the main() method
 
import java.io.*;
 
class GFG {
 
    // The method that calls the main() method
    static void mainCaller()
    {
        System.out.println("mainCaller!");
 
        // Calling the main() method
        main(null);
    }
 
    // main() method
    public static void main(String[] args)
    {
        System.out.println("main");
 
        // Calling the mainCaller() method
        // so that main() method is called externally
        mainCaller();
    }
}
  • Error de tiempo de ejecución en código Java:
RunTime Error in java code :-
 Exception in thread "main" java.lang.StackOverflowError

mainCaller!
main
mainCaller!
main
mainCaller!
main
.
.
.

La forma correcta de hacerlo:
Ejemplo 1: Llamar al método main() externamente desde la misma clase 

Java

// Java method to show Calling main() method
// externally from the same class
 
import java.io.*;
 
class GFG {
 
    static int count = 0;
 
    // The method that calls the main() method
    static void mainCaller()
    {
 
        System.out.println("mainCaller!");
        count++;
 
        // Calling the main() only 3 times
        if (count < 3) {
 
            // Calling the main() method
            main(null);
        }
    }
 
    // main() method
    public static void main(String[] args)
    {
        System.out.println("main");
 
        // Calling the mainCaller() method
        // so that main() method is called externally
        mainCaller();
    }
}

Producción:  

main
mainCaller!
main
mainCaller!
main
mainCaller!

Ejemplo 1: llamar al método main() externamente desde otra clase 

Java

// Java method to show Calling main() method
// externally from another class
 
import java.io.*;
 
class GFG {
 
    static int count = 0;
 
    // The method that calls the main() method
    static void mainCaller()
    {
 
        System.out.println("mainCaller!");
        count++;
 
        // Calling the main() only 3 times
        if (count < 3) {
 
            // Calling the main() method
            Test.main(null);
        }
    }
}
 
class Test {
 
    // main() method
    public static void main(String[] args)
    {
        System.out.println("main");
 
        // Calling the mainCaller() method
        // so that main() method is called externally
        GFG.mainCaller();
    }
}

Producción: 

main
mainCaller!
main
mainCaller!
main
mainCaller!

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *