Search code examples
javaclassjvmmain-method

Why JVM cannot create object of class containing main method in order to access main method from that class, if it has the name of that class?


Well, I am not understanding that why JVM cannot create object of class having main method.

If JVM can access main method by the name of that class then definitely it can create an object of that class right!

But what is the reason behind accessing main method by class name?

I am asking this question because, if JVM has the name of class to access main method then it definitely can create object of that class by using that name.


Solution

  • I think you are asking (in effect) why you cannot write your "main" method like this:

    // (Note: this does not work ...)
    public class Test {
        public void main(String[] args) {
            System.out.println("Hello world");
       }
    }
    

    NB: main is not static in the above ...

    The answer is:

    1. Because that is not the way that Java was designed ... in the 1990's.

    2. We cannot tell you why they designed Java that way, because we weren't in the room when the decision was made.

    3. We can infer that the reason that the (current) Java team haven't extended Java to allow you to do the above is because there isn't a pressing need to do so. In fact, the static "main" method approach works fine. There is a saying that goes:

      If it ain't broken, don't fix it.

    If you want your application's entry point to be via an object, it is trivial for you to code it to work that way. For example:

    public class Test {
    
        public static void main(String[] args) {
            new Test().main(args);
        }
    
        private void main(String[] args) {
            System.out.println("Hello world");
        }
    }
    

    That's just 3 lines of extra code.

    Note that the static main method is the simplest approach from the perspective of the specification of Java and the implementation of Java.