Why We Need Static Methods
Before we can call a dynamic method using the
x.f(...)
syntax,
we have to create the object x
that will act as receiver for the call.
When a Java program first begins to execute, before any objects have been created, there are no objects that could act as receiver for a dynamic method call.
To create the first objects, we have to call at least one static method.
In Java, the first method called is the static method
named main
that is defined in the class
we named on the command line that invoked the JVM.
If we invoke the JVM by saying java C
,
then the JVM starts the program by calling the
static main
method defined in class C
.
If we invoke the JVM by saying java Foo
,
then the JVM starts the program by calling the
static main
method defined in class Foo
.
A Java program can therefore have multiple main entry points, each defined in a separate class. As will be explained in the next lesson, multiple entry points are convenient for unit testing.