Java Reference
In-Depth Information
9.
10. public Room getKitchen() {
11. counter++;
12. return kitchen;
13. }
14. }
The counter fi eld is a class variable. There is only one instance of counter in memory,
and it exists in memory before any House objects are instantiated.
Access a class variable using the name of the class. For example, to access counter you
use the following syntax:
House.counter
Notice on line 11 that counter was incremented and we did not use the name of the
class to reference it. Code within the class that contains the static fi eld does not need to use
the class name.
Examine the following HouseTest program. Does it compile, and if so, what is its
output?
1. import my.blueprints.House;
2.
3. public class HouseTest {
4. public static void main(String [] args) {
5. System.out.println(“counter = “ + House.counter);
6. House one = new House();
7. House two = new House();
8. one.getKitchen();
9. two.getKitchen();
10. one.getKitchen();
11. System.out.println(“counter = “ + House.counter);
12. }
13. }
On line 5 the counter variable displays before any House objects are created. This is a
valid statement and the value of counter is 0 at line 5. Two House objects are instantiated,
and calling getKitchen three times on the two House objects increments counter to 3. The
code compiles successfully and the output is
counter = 0
counter = 3
Even though the HouseTest class creates two House objects (which in turn causes two
Room objects to be instantiated for the kitchen fi eld), there is still only one counter in
memory and it exists until the program terminates.
Search WWH ::




Custom Search