Monday, April 30, 2012

Why main() method in Java is static?

Java is strictly Object-Oriented language. Java does not support open functions like C and C++. In Java data and methods are written inside a class. Like C and C++ java application’s entry point is main() method.  main() method is coded inside a Starter class. This is an interesting scenario  . A method of a class can be invoked using its object reference. Now the question is where will you create this object?  object can be created inside another  class e.g.
public class A {
      public void sayHello() {
              System.out.println(“Hello from Java”);
      }
}

To test class A, I create a StartA class.
public  class StartA {
      public void main(String args[]) { // main needs to be public, as will be invoked from outside the class
               A ob = new A();
               ob.sayHello();
      }
}
To call sayHello() method
Class A’s object is created in StatrtA class.  sayHello() method is called by its object reference of class A.   Every application’s execution start from main().  To call main(), an object of StartA class needs to be created. To create an object of StartA class, another class is needed… . So,  create another class to create an object of StartA class, then where can the object be created for that class. Create another class for that and then what next? It will be never ending story.  In this black box, make  a hole and let the main () method slip out. This hole can be created by declaring main() as static method.  A static member belongs to a class and not to the object. By declaring main() method as static, JVM can call main() by its class name i.e StartA.main().  Java’s beauty is in its simplicity.
 StartA class can be coded as :
public  class StartA {
      public static void main(String args[]) { // main needs to be static to be called by its class name
               A ob = new A();
               ob.sayHello();
      }
}


3 comments:

  1. .. and just to add on..

    How does JVM call the main class? By its class name: StartA.main(...);
    In fact, it is always like that, i.e. ClassName.main(args);

    Now, where does it get the class name? ah, that's when you do "java ClassName arg01 arg02" ..

    ReplyDelete
  2. Thanks Clarence for valuable info

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete