Java Reference
In-Depth Information
UML Notation:
underline: static variables or methods
instantiate
circle1: Circle
Memory
After two Circle
Objects were created,
numberOfObjects
is 2.
radius = 1
numberOfObjects = 2
1
radius
Circle
radius: double
numberOfObjects: int
numberOfObjects
2
getNumberOfObjects(): int
getArea(): double
instantiate
circle2: Circle
radius = 5
numberOfObjects = 2
radius
5
F IGURE 8.13 Instance variables belong to the instances and have memory storage independent of one another. Static
variables are shared by all the instances of the same class.
To declare a static variable or define a static method, put the modifier static in the vari-
able or method declaration. The static variable numberOfObjects and the static method
getNumberOfObjects() can be declared as follows:
static
int numberOfObjects;
declare static variable
static
int getNumberObjects() {
return numberOfObjects;
define static method
}
Constants in a class are shared by all objects of the class. Thus, constants should be declared
as final static . For example, the constant PI in the Math class is defined as:
declare constant
final static double PI = 3.14159265358979323846 ;
The new circle class, named CircleWithStaticMembers , is defined in Listing 8.7:
L ISTING 8.7 CircleWithStaticMembers.java
1
public class CircleWithStaticMembers {
2
/** The radius of the circle */
3
double radius;
4
5
/** The number of objects created */
6
7
8 /** Construct a circle with radius 1 */
9 CircleWithStaticMembers() {
10 radius = 1 ;
11
12 }
13
14 /** Construct a circle with a specified radius */
15 CircleWithStaticMembers( double newRadius) {
16 radius = newRadius;
17
18 }
19
20
static int numberOfObjects = 0 ;
static variable
numberOfObjects++;
increase by 1
numberOfObjects++;
increase by 1
/** Return numberOfObjects */
21
22
static int getNumberOfObjects() {
static method
return numberOfObjects;
23 }
24
 
Search WWH ::




Custom Search