Can the "main ()" method be overloaded or overwritten?

I read the answer What does public static void main(String[] args) mean?, but I still have two doubts about the method main():

  1. can the main() method be overloaded?
  2. can the main() method be overwritten?
Author: Maniero, 2019-02-27

3 answers

Yes, it can be overloaded, but only the original method is called by the JVM. As for overwriting, it can not, as it is static.

References: overwritten and overload

 4
Author: renanvm, 2019-02-27 19:59:28

In Java the esse main() referenced in that question cannot be overloaded.

Of course you can overload a method called main() but it doesn't have the special feature that it deals with that question. Any overhead in this name has nothing to do with the concept of being an application entry point and Java only has one overhead accepted, which is the one shown. So the answer depends on what you mean in your question. My interpretation is that you want to know about this method in particular.

In C # there are some overloads accepted as entry point (it has signature with different parameters, different returns and even asynchronicity), yet only a few, all the infinite possibilities of different signatures are common methods that happen to have the name Main(), but it has nothing to do with this method with special features.

And cannot be overwritten , for the simple reason that it is static and methods statics are part of the class and not the instance, and only instance members make sense to be inherited. Inheritance comes true when you create an instance, so an object has all its members plus the members of the parent type. The static method exists by itself, without relying on instance.

One might question whether the method could not be static. It could, but it would be a great difficulty to deal with it without any major advantage.

 6
Author: Maniero, 2020-08-31 20:32:21
  1. No. The main method is the starting point of your application. If you overload it, it means that its signature will change and it will be treated as any method and your program will not be able to run.

Your class with the "differentiated" main method could still be invoked and used across other classes normally.

But to run your program, somewhere there must be a class with a main method with the signature identical to the one you already have know.

public static void main(String[]);
  1. No. Static methods cannot be overwritten. Overriding is a feature of Instance Methods.

Static methods can be hidden. But I don't know what good practices say about it.

Https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.8

Having a super class and a subclass, each with its own main method means that your program would have 2 entry points. Whatever problem you are trying to solve, for sure there is a design pattern that would be more suitable.

 2
Author: wldomiciano, 2019-02-27 20:08:31