Java Reference
In-Depth Information
// Invoke the class method using the class name
MethodType.printM();
System.out.println("Invoking class method on an instance...");
// Invoke the class method using the instance reference
mt.printM();
}
}
Invoking instance method...
printMN() - m = 100
printMN() - n = 200
Invoking class method on class name...
printM() - m = 100
Invoking class method on an instance...
printM() - m = 100
The Special main() Method
You learned about declaring a method in a class in the previous section. Let's discuss the
main()
method that you
have been using to run your classes. The
main()
method declaration is as follows:
public static void main(String[] args) {
// Method body goes here
}
Two modifiers,
public
and
static
, are used in the declaration of the
main()
method. The
public
modifier makes
it accessible from anywhere in the application as long as the class in which it is declared is accessible. The
static
modifier makes it a class method, so it can be invoked using a class name. Its return type is
void
, which means it does
not return a value to its caller. Its name is
main
and it accepts one parameter of type
String
array (
String[]
). Note
that you have been using
args
as the name of its parameter. However, you can use any parameter name you wish. For
example, you can declare the
main
method as
public static void main(String[] myParameters)
, which is the
same as declaring the
main
method as shown above. Whatever parameter name you choose, you will need to use the
same name in the body of the method if you need to refer to the parameter passed to this method.
What is special about the declaration of a
main()
method in a class? You run a Java application by passing a class
name to the
java
command. For example, you would use the following command to run the
MethodTypeTest
class:
java com.jdojo.cls.MethodTypeTest
When the above command is executed, the JVM (the
java
command essentially starts a JVM) finds and loads
the
MethodType
class definition in memory. Then, it looks for a method declaration, which is declared as
public
and
static
, returns
void
, and has a method argument as
String
array. If it finds the
main()
method declaration, the
JVM invokes the method. If it does not find the
main()
method, it does not know where to start the application and it
throws an error stating that no
main()
method was found.