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

Asked

Viewed 209 times

1

3 answers

6

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

Of course you can overload a method called main() But he doesn’t have the special characteristic that it addresses that question. Any overload in this name has nothing to do with the concept of being an application entry point and Java only has an accepted overload, 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 particular method.

In C# there are some overloads accepted as entry point (has signing 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 has nothing to do with this method with special features.

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

One might wonder if the method might not be static. I might, but it would be a great deal of trouble to deal with without any major advantage.

4


Yes, it can be overloaded, but only the original method is called by the JVM. As for the superscript, it cannot because it is static.

References: Superscript and Overload

  • 1

    Thanks renanzin, I completely forgot the static method on the envelope.

2

  1. No. The main method is the starting point of its application. If you overload it, it means that its signature will change and it will be treated as any method and your program cannot be run.

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

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

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

Static methods can be hidden (Hiding). But I don’t know what good practice says about this.

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 its program would have 2 entry points. Whatever problem you’re trying to solve, surely there is a design pattern that would be more appropriate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.