Contenido del Curso
Java Extended
Java Extended
Main Class and Method
Main class
Earlier, we work with the class named Main, but why?
Main
serves as the entry point of the application, the starting point. It is in the main
method that we execute everything we have written earlier. The name Main
should remain unchanged so the compiler recognizes it as our entry point.
Within the main
method, we can write many methods, but they must be static and marked with the static
keyword.
Static
The keyword static
in Java is used to declare a member (variable or method) that belongs to the class itself rather than an instance of the class. Here's a simple explanation:
- Static Variables: When a variable is declared as static, there is only one copy of that variable shared by all instances of the class. It means that any changes made to the variable will be reflected across all instances of the class;
- Static Methods: When a method is declared as static, it can be invoked directly on the class itself without needing an instance of the class. Static methods are commonly used for utility methods or operations that don't require accessing instance-specific data.
That's why we were able to use the methods created in the Main
class within the main
method. We didn't have to create an instance of the Main
class (although it is possible) to invoke a method on it.
Why Should the main Method in Java Be Static?
The main
method is the entry point of a Java program, and it needs to be static because it needs to be called without creating an instance of the class. When the Java Virtual Machine (JVM) starts executing a Java program, it looks for the main
method with the specific signature (public static void main(String[] args)
) to begin the execution. Since the main method is called directly on the class, it must be static so that the JVM can access it without creating an object.
¡Gracias por tus comentarios!