How to overload and override main method in Java
How to overload main method in java?
Method Overloading can be defined as a feature in which a class can have more than one method having the same name if and only if they differ by number of parameters or the type of parameters or both, then they may or may not have same return type. Method overloading is one of the ways that java support Polymorphism.
Yes, We can overload the main method in java but JVM only calls the original main method, it will never call our overloaded main method.
Below example illustrates the overloading of main() in java
As from above example, it is clear that every time original main method executes but not the overloaded methods because JVM only executes the original main method by default but not the overloaded one.
So, to execute overloaded methods of main, we must call them from the original main method.
In this example, we will execute all the Overloads of the main method one by one
Original main() Executing Hello main() overloaded method 1 Executing true main() overloaded method 2 Executing Geeks For Geeks main() overloaded method 3 Executing 987654
Overriding main() method in java?
Whenever we do inheritance in java then if a method in subclass has the same name and type signature as a method in its parent class or superclass, then it is said that the method in subclass is overriding the method of parent class. Method overriding is one of the way that java supports run time Polymorphism.
No, we cannot override main method of java because a static method cannot be overridden.
The static method in java is associated with class whereas the non-static method is associated with an object. Static belongs to the class area, static methods don’t need an object to be called. Static methods can be called directly by using the classname ( classname.static_method_name() ).
So, whenever we try to execute the derived class static method, it will automatically execute the base class static method.
Therefore, it is not possible to override the main method in java.
To know more about Overriding static method in java Visit here