Java Reference
In-Depth Information
To run this program, you enter the following command:
java ConstructorDemo
The ConstructorDemo class has no fields and one method. At no point in
time did we instantiate a ConstructorDemo object. So how can the JVM invoke
a method in a class if no instances of the class exist? Remember, a class is only
a definition. Fields and methods do not exist until the class is instantiated.
Well, actually, that last sentence is only partly true. To be more accurate, the
nonstatic fields and methods of a class do not exist until the class is instanti-
ated. However, static members are associated with the class. Static fields and
methods are allocated in memory and can be used once the class is loaded by
the JVM. (Class loading takes place throughout a program's execution as
classes are needed by the JVM.)
Because main() is static in ConstructorDemo, main() can be invoked without
requiring a new ConstructorDemo object to be instantiated. The question now
becomes: If we don't need an instance of a class to invoke a static method or
access a static field, what is the syntax for accessing a static member? The
answer is to use the name of the class, which is discussed next.
Accessing Static Fields and Methods
Static fields and methods are not accessed using a reference because references
refer to instances of the class, and we do not need instances of the class to
access static members. Instead, the name of the class is used to access a static
member.
For example, if you wanted to invoke main() in the ConstructorDemo class,
you would use the syntax:
ConstructorDemo.main(null); //Or replace null with an array of String's
Of course, main() is not a method we typically invoke because the JVM does
that for us. Notice that if the JVM wants to invoke main(), the JVM needs the
name of the class. But we give the JVM the name of the class when we run the
program:
java ConstructorDemo
And now you know why the java command requires the name of the class
that contains main().
We have used static fields and methods in the examples and labs. You can
tell when a field or method is static whenever you see it being accessed with a
class name. For example, throughout the topic we have used:
System.out
Search WWH ::




Custom Search