Java Reference
In-Depth Information
Because static methods do not operate in the context of a particular object,
they cannot reference instance variables, which exist only in an instance of a class.
The compiler will issue an error if a static method attempts to use a nonstatic
variable. A static method can, however, reference static variables, because static
variables exist independent of specific objects. Therefore, the
main
method can
access only static or local variables.
The program in Listing 7.1 instantiates several objects of the
Slogan
class,
printing each one out in turn. At the end of the program it invokes a method
called
getCount
through the class name, which returns the number of
Slogan
objects that were instantiated in the program.
LISTING 7.1
//********************************************************************
// SloganCounter.java Author: Lewis/Loftus
//
// Demonstrates the use of the static modifier.
//********************************************************************
public class
SloganCounter
{
//-----------------------------------------------------------------
// Creates several Slogan objects and prints the number of
// objects that were created.
//-----------------------------------------------------------------
public static void
main (String[] args)
{
Slogan obj;
obj =
new
Slogan ("Remember the Alamo.");
System.out.println (obj);
obj =
new
Slogan ("Don't Worry. Be Happy.");
System.out.println (obj);
obj =
new
Slogan ("Live Free or Die.");
System.out.println (obj);
obj =
new
Slogan ("Talk is Cheap.");
System.out.println (obj);
obj =
new
Slogan ("Write Once, Run Anywhere.");
System.out.println (obj);
Search WWH ::
Custom Search