Java Reference
In-Depth Information
field. The last form is preferable, because it communicates to the reader that
the field is indeed a static field. Another example of a static field is the con-
stant Math.PI .
Even without the final qualifier, static fields are still useful. Figure 3.9
illustrates a typical example. Here we want to construct Ticket objects, giving
each ticket a unique serial number. In order to do this, we have to have some
way of keeping track of all the previously used serial numbers; this is clearly
shared data, and not part of any one Ticket object.
Each Ticket object will have its instance member serialNumber ; this is
instance data because each instance of Ticket has its own serialNumber field.
All Ticket objects will share the variable ticketCount , which denotes the
number of Ticket objects that have been created. This variable is part of the
class, rather than object-specific, so it is declared static . There is only
one ticketCount , whether there is 1 Ticket , 10 Ticket s, or even no Ticket
objects. The last point—that the static data exists even before any
instances of the class are created—is important, because it means the static
data cannot be initialized in constructors. One way of doing the initializa-
tion is inline, when the field is declared. More complex initialization is
described in Section 3.6.6.
In Figure 3.9, we can now see that construction of Ticket objects is done
by using ticketCount as the serial number, and incrementing ticketCount . We
also provide a static method, getTicketCount , that returns the number of tick-
ets. Because it is static, it can be invoked without providing an object refer-
ence, as shown on lines 36 and 41. The call on line 41 could have been made
using either t1 or t2 , though many argue that invoking a static method using
an object reference is poor style, and we would never do so in this text. How-
ever, it is significant that the call on line 36 clearly could not be made through
an object reference, since at this point there are no valid Ticket objects. This is
why it is important for getTicketCount to be declared as a static method; if it
was declared as an instance method, it could only be called through an object
reference.
A static field is
shared by all
(possibly zero)
instances of the
class.
When a method is declared as a static method, there is no implicit this ref-
erence. As such, it cannot access instance data or call instance methods, without
providing an object reference. In other words, from inside getTicketCount ,
unqualified access of serialNumber would imply this.serialNumber , but since
there is no this , the compiler will issue an error message. Thus, a nonstatic
field, which is part of each instance of the class, can be accessed by a static
class method only if a controlling object is provided.
A static method
has no implicit
this reference, and
can be invoked
without an object
reference.
Search WWH ::




Custom Search