Java Reference
In-Depth Information
Listing 6-9.
A MainTest1 Class, Which Declares a main() Method
// MainTest1.java
package com.jdojo.cls;
public class MainTest1 {
public static void main(String[] args) {
System.out.println("Inside main() method of the MainTest1 class.");
}
}
Listing 6-10.
A MainTest2 Class, Which Declares a main() Method, Which in Turn Calls the main() Method of the
MainTest1 Class
// MainTest2.java
package com.jdojo.cls;
public class MainTest2 {
public static void main(String[] args) {
MainTest1.main(args);
}
}
Inside main() method of the MainTest1 class.
The
main()
method of the
MainTest2
class invokes the
main()
method of the
MainTest1
class using the
following code:
MainTest1.main(null);
Note that the
main()
method of the
MainTest1
class accepts a
String
array as a parameter and the above
statement passes
null
as the actual value for that parameter. I will discuss arrays in detail in the chapter on arrays. You
run the
MainTest2
class as
java com.jdojo.cls.MainTest2
The JVM will invoke the
main()
method of the
MainTest2
class, which in turn invokes the
main()
method of the
MainTest1
class. The output in Listing 6-10 confirms this. You can also let the JVM invoke the
main()
method of the
MainTest1
class by running the
MainTest1
class as
java com.jdojo.cls.MainTest1
■
the
main()
method in a class, which is declared as
public static void main(String[] args)
, has a special
meaning only when the class is run by the jVM. It serves as an entry point for the java application. Otherwise, the
main()
method is treated the same as any other class methods.
Tip