Overload and override main method in Java
This post will discuss how to overload and override the main method in Java.
We know that the main method in Java serves as an entry point for any program. It has a fixed signature that is recognized by the JVM (Java Virtual Machine). The JVM starts its execution by invoking the main method of the specified class, and the main() method will subsequently invoke all the other methods required by the program.
It is possible to overload the main() method in Java, which means to have more than one method with the same name but different parameters. We can have any number of main methods defined in a Java class with different method signatures, but the class should contain one main method with exact signature as public static void main(String[] args). If no such method exist, the program will compile successfully but throws the following runtime error upon execution:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Here is an example of overloading the main method in Java. We have a main method that takes an integer as an argument, and another main method that takes a double as an argument. However, the JVM will not automatically invoke these overloaded main methods. They need to be called manually from the original main method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Main { // Overloaded main method that takes an int argument public static void main(int i) { System.out.println("Inside overloaded main: " + i); } // Overloaded main method that takes a double argument public static void main(double d) { System.out.println("Inside overloaded main: " + d); } // Original main method public static void main(String[] args) { System.out.println("Inside main"); main(7); main(3.14); } } |
Output:
Inside main
Inside overloaded main: 7
Inside overloaded main: 3.14
However, it is not possible to override the main method in Java, which means to have a different implementation of the same method in a subclass. This is because the main method is a static method, and static methods cannot be overridden in Java. The method overriding only occurs in the context of dynamic lookup of methods and static methods are looked up statically at compile-time itself. The static methods belong to the class itself and are not associated with any object. Therefore, if we try to override the main method in a subclass, the JVM will not treat the main method in a subclass as the starting point of the program. It will be a regular static method that we can invoke by using the name of the subclass.
That’s all about overloading and overriding the main method in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)