Java Reference
In-Depth Information
To invoke the getCounter() method, use the syntax:
Employee.getCounter()
Study the StaticDemo and try to determine its output, which is shown in
Figure 7.6.
public class StaticDemo
{
public static void main(String [] args)
{
Employee.counter = 100;
System.out.println(“Counter = “ + Employee.getCounter());
Employee e = new Employee(“John Wayne”,
“101 Hollywood Blvd.”, 123456789);
System.out.println(“Counter now = “ + Employee.getCounter());
System.out.println(“Using e: “ + e.getCounter());
}
}
The first statement within main() of the StaticDemo class is:
Employee.counter = 100;
Notice that there are no Employee objects in memory yet. We can only
access counter because it is static and the counter field was created in memory
when the Employee class was loaded (which would be right away when the
program begins executing). The counter field is 100, which is printed out with
the statement:
System.out.println(“Counter = “ + Employee.getCounter());
Again, we used the class name to invoke getCounter(), which exists in mem-
ory even though no Employee objects have been instantiated yet.
Figure 7.6
Output of the StaticDemo program.
Search WWH ::




Custom Search