javastaticjvmprogram-entry-point

How does the compiler handle Main when instantiating own class


EDIT: For clarification:

Create a new class containing static main. Instantiate the same class during the main method. What does the JVM do when it arrives at that main method line of code as it is instantiating it?

(How does the JVM know to "skip over" the static main() method in the following code during the while loop)

I'm asking because I can't see any benefit to put static main into a class that you intend to instantiate, it seems much better to only ever put static main into a "launcher" class, built solely for the purpose of launching the application..

Confusing for the dog class:

public class Dog {
    private int height;

    public static void main (String[] args) { // <---- What does the JVM do when it reaches here during the object instantiation?
        int i = 0;
        Dog [] dogArray = new Dog[20];
        while (i < 20){
             dogArray[i] = new Dog(); // Instantiate knew class
             dogArray[i].height = i*10; //whatever
             i++;
        }
    }
}

Surely it is always better to create two classes, in this case:

public class Dog {
    private int height;

    getHeight{//etc...}
    setHeight{//etc...}
}

public class launchApplication{
public static void main (String[] args) {
    int i = 0;
    Dog [] dogArray = new Dog[20];
    while (i < 20){
         dogArray[i] = new Dog(); // Instantiate knew class
         dogArray[i].setHeight = i*10; //whatever
         i++;
    }
}

}


Solution

  • It turns out the answer I was looking for (and the question I was trying to ask) was actually how the JVM goes about bootstrapping and invoking main. It is native code that first starts the JVM and the main method is called using STATIC so as to avoid having to somehow (externally) create an object first, and then call the main method from that object.

    The confusion I had over why the main method was "ignored" was a misunderstanding of how that main method is called - it is called explicitly by the JVM during it's launch, and this, is the JAVA convention - The JVM is built and designed this way, it is a dedicated method.

    So in my example, main, being a method, is not called during each instantiation of the class that main belongs to (because methods are not implicitly called during instantiation), I was under the impression that main was somehow automatically called whenever a class is instantiated by virtue of it being "the java main method" - as if it had a hook to be called. The key was in grasping STATIC and how the JVM loads the Main method without having it's enclosing class instantiated first. This essentially is the transition from the JVM (including native) bootstrap procedural process into the more "purer" object oriented capability of the running JAVA application.

    Hope that makes sense, and hope it might help someone clarify something.