Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override main method

Tags:

java

Can we override the method as mentioned below:-

"public static void main"

like image 457
Milan Mendpara Avatar asked Jan 31 '12 17:01

Milan Mendpara


People also ask

What happens when we override main method?

Overriding main methodYou cannot override static methods and since the public static void main() method is static we cannot override it.

What happens if we override main method in Java?

Java main() Method Overloading The JVM starts the execution of any Java program form the main() method. Without the main() method, JVM will not execute the program.


2 Answers

No. main is a static method, and is thus not polymorphic. You may hide it be defining another static main method in a subclass, though.

like image 90
JB Nizet Avatar answered Sep 29 '22 13:09

JB Nizet


No and you are losing the focus here. The main method has a single purpose and is declared logically for that sole purpose:

The main method in Java belongs to a class but not to an Object. Objects are created at The main() in Java is the start point in your application, there is no way to start your application from an instance specific method. That is why the static keyword make perfect sense with the main method. In fact all the parts of the main method declaration make perfect sense when you think like the 'jvm' and picture what the main method does (starts the application):

  • public, because this method must be accessible by the jvm (not written by you).
  • static, implying this method can be accessed without having an object (because it's representation never changes), but here the logic is easy understood if you think like the jvm again; "I don't have any objects to create (instantiate) objects, so I need a static method to start the application as there simple isn't any logical way to get an instance specific method up yet as I don't have anything up yet to create objects".
  • void This method can't logically return anything because there is nothing up yet to return anything to. It is the start point of the application. main I am the main method as without me you won't have an application.
  • String[] args Send me data you may feel useful for my startup.
like image 27
thejartender Avatar answered Sep 29 '22 13:09

thejartender