Java Reference
In-Depth Information
ing executed. If you don't do this, once you call the method, it will never return. This type
of error is very common when working with recursion. Use println( ) statements liberally
so that you can watch what is going on and abort execution if you see that you have made
a mistake.
Understanding static
There will be times when you will want to define a class member that will be used inde-
pendently of any object of that class. Normally a class member must be accessed through
an object of its class, but it is possible to create a member that can be used by itself, without
reference to a specific instance. To create such a member, precede its declaration with the
keyword static . When a member is declared static , it can be accessed before any objects of
its class are created, and without reference to any object. You can declare both methods and
variables to be static . The most common example of a static member is main( ) . main( )
is declared as static because it must be called by the JVM when your program begins. Out-
side the class, to use a static member, you need only specify the name of its class followed
by the dot operator. No object needs to be created. For example, if you want to assign the
value 10 to a static variable called count that is part of the Timer class, use this line:
This format is similar to that used to access normal instance variables through an object,
except that the class name is used. A static method can be called in the same way—by use
of the dot operator on the name of the class.
Variables declared as static are, essentially, global variables. When an object is declared,
no copy of a static variable is made. Instead, all instances of the class share the same static
variable. Here is an example that shows the differences between a static variable and an
instance variable:
Search WWH ::




Custom Search