Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 4 Advanced Class Design

Using the “static” Keyword

Suppose that you wanted a write a simple class that counts the number of objects of its class type created so far. Will the program in Listing 4-2 work?

Listing 4-2.  Counter.java

// Counter class should count the number of instances created from that class public class Counter {

private int count; // variable to store the number of objects created

//for every Counter object created, the default constructor will be called;

//so, update the counter value inside the default constructor

public Counter() { count++;

}

public void printCount() { // method to print the counter value so far System.out.println("Number of instances created so far is: " + count);

}

public static void main(String []args) { Counter anInstance = new Counter(); anInstance.printCount();

Counter anotherInstance = new Counter(); anotherInstance.printCount();

}

}

The output of the program is

Number of instances created so far is: 1 Number of instances created so far is: 1

Oops! From the output, it is clear that the class does not keep track of the number of objects created. What happened?

You’ve used an instance variable count to keep track of the number of objects created from that class. Since every instance of the class has the value count, it always prints 1! What you need is a variable that can be shared across all its instances. This can be achieved by declaring a variable static. A static variable is associated with its class rather than its object; hence they are known as class variables. A static variable is initialized only once when execution of the program starts. A static variable shares its state with all instances of the class. You access a static variable using its class name (instead of an instance). Listing 4-3 shows the correct implementation of the Counter class with both the count variable and the printCount method declared static.

Listing 4-3.  Counter.java

// Counter class should count the number of instances created from that class public class Counter {

private static int count; // variable to store the number of objects created

//for every Counter object created, the default constructor will be called;

//so, update the counter value inside the default constructor

public Counter() { count++;

}

92

Chapter 4 Advanced Class Design

public static void printCount() { // method to print the counter value so far System.out.println("Number of instances created so far is: " + count);

}

public static void main(String []args) { Counter anInstance = new Counter();

// note how we call printCount using the class name instead of instance variable name Counter.printCount();

Counter anotherInstance = new Counter(); Counter.printCount();

}

}

This program prints

Number of instances created so far is: 1 Number of instances created so far is: 2

Here, the static variable count is initialized when the execution started. At the time of first object creation, the count is incremented to one. Similarly, when second object got created, the value of the count became 2. As the output of the program shows, both objects updated the same copy of the count variable.

Note how we changed the call to printCount() to use class name Counter, as in Counter.printCount().

The compiler will accept the previous two calls of anInstance.printCount() and anotherInstance.printCount() as there is no semantic difference between calling a static method using a class name or instance variable name. However, to use instance variables to call static methods is not recommended. It is conventional practice to call instance methods using instance variables and to call static methods using class names.

A static method can only access static variables and can call only static methods. In contrast, an instance method (non-static) may call a static method or access a static variable.

Static Block

Apart from static variables and methods, you can also define a static block in your class definition. This static block will be executed by JVM when it loads the class into memory. For instance, in the previous example, you can define a static block to initialize the count variable to default 1 instead of the default value 0, as shown in Listing 4-4.

Listing 4-4.  Counter.java

public class Counter {

private static int count; static {

// code in this static block will be executed when JVM loads the class into memory count = 1;

}

public Counter() { count++;

}

public static void printCount() {

System.out.println("Number of instances created so far is: " + count);

}

public static void main(String []args) { Counter anInstance = new Counter(); Counter.printCount();

93

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]