Java is a 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 applications’ entry point is the main method. The 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? An 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. The sayHello() method is called by the object reference of class A. Every application’s execution starts from main(). To call main(), an object of the StartA class needs to be created. To create an object of the StartA class, another class is needed…. So, create another class to create an object of the StartA class, then where can the object be created for that class? Create another class for that, and then what next? It will be a 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 a static method. A static member belongs to a class and not to the object. By declaring the main() method as static, the JVM can call the 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();
}
}
.. and just to add on..
ReplyDeleteHow 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" ..
Thanks Clarence for valuable info
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete