When it comes to order/sequence methods in java class.
Where do you expect/prefer to see main()
method?
Please share your thoughts, this is kind of stylistic/philosophical question.
Please do not suggest to keep main()
in separate file alone.
Most (if not all) of the standard JDK libraries will follow it. This is IMHO a good reason to go with the methods-last approach. Regarding the placement of main among the methods, putting it first or last would work. If you find it "special" in some way, then put it dead last in the file.
When you launch your program, the class with the main method is loaded by the JVM's bootstrap class loader. A Java class loader adds the methods of each class loaded into the JVM's method area, which is a shared memory pool where all the executable code for Java classes goes.
The main() method must be called from a static method only inside the same class.
Therefore, java main() method is the starting place of your program. The syntax for declaration of the java main method is as follows: Syntax: public static void main(String[] args) { // Method body goes here. } In the above declaration, two modifiers such as public, and static has been used with the main method.
These are just my thoughts:
main() is a static method unrelated to object instances. We know that it exists as an entry point, that makes our program/class executable.
The thing is that in Java, everything (but primitives) is an object, so main() must be declared in some class somewhere. The code such a static method may execute is more concerned with setting up the program for execution, and delegating to our business logic (objects that actually do something) to run the application. As such, its concern is distinct from the rest of our class (which defines some data and behaviour that we are trying to encapsulate).
main() doesn't really belong with the data and behaviour of our everyday classes, as I doubt that every class needs to be executable on its own. main()'s concern is with running our program. As such, it should be declared away from our business objects, in a module of the project concerned with application launch/execution. So, as you might be guessing, I am proposing exactly what you've said not to suggest - keep main away from your classes and logic as much as possible, and only declare it in the context of an entry point to your application.
As to the location within a file itself, I don't really think it matters - as long as it is obvious that the code in that file is concerned with setting up and running the program.
I've always put it at the end, because that's how they do it in C. "Tradition". Which may not be that good of a reason. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With