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
radius
1
Circle
radius: double
numberOfObjects: int
numberOfObjects
2
getNumberOfObjects(): int
getArea(): double
instantiate
circle2: Circle
radius = 5
numberOfObjects = 2
radius
5
F IGURE 9.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.
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 9.6:
L ISTING 9.6
CircleWithStaticMembers.java
1 public class CircleWithStaticMembers {
2
/** The radius of the circle */
3
double radius;
4
5
/** The number of objects created */
6
static int numberOfObjects = 0 ;
static variable
7
8 /** Construct a circle with radius 1 */
9 CircleWithStaticMembers() {
10 radius = 1 ;
11
numberOfObjects++;
increase by 1
12 }
13
14 /** Construct a circle with a specified radius */
15 CircleWithStaticMembers( double newRadius) {
16 radius = newRadius;
17
numberOfObjects++;
increase by 1
18 }
19
20
/** Return numberOfObjects */
21
static int getNumberOfObjects() {
static method
22
return numberOfObjects;
23 }
24
25
/** Return the area of this circle */
26
double getArea() {
27
return radius * radius * Math.PI;
28 }
29 }
Method getNumberOfObjects() in CircleWithStaticMembers is a static method. All
the methods in the Math class are static. The main method is static, too.
 
 
Search WWH ::




Custom Search