19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

8.7 Static Variables, Constants, and Methods 313<br />

UML Notation:<br />

underline: static variables or methods<br />

Circle<br />

radius: double<br />

numberOfObjects: int<br />

getNumberOfObjects(): int<br />

getArea(): double<br />

instantiate<br />

instantiate<br />

circle1: Circle<br />

radius = 1<br />

numberOfObjects = 2<br />

circle2: Circle<br />

Memory<br />

1<br />

2<br />

radius<br />

numberOfObjects<br />

After two Circle<br />

Objects were created,<br />

numberOfObjects<br />

is 2.<br />

radius = 5<br />

numberOfObjects = 2<br />

5<br />

radius<br />

FIGURE 8.13 Instance variables belong <strong>to</strong> the instances and have memory s<strong>to</strong>rage independent of one another. Static<br />

variables are shared by all the instances of the same class.<br />

To declare a static variable or define a static method, put the modifier static in the variable<br />

or method declaration. The static variable numberOfObjects and the static method<br />

getNumberOfObjects() can be declared as follows:<br />

static<br />

int numberOfObjects;<br />

declare static variable<br />

static int getNumberObjects() {<br />

return numberOfObjects;<br />

}<br />

Constants in a class are shared by all objects of the class. Thus, constants should be declared<br />

as final static. For example, the constant PI in the Math class is defined as:<br />

define static method<br />

declare constant<br />

final static double PI = 3.14159265358979323846;<br />

The new circle class, named CircleWithStaticMembers, is defined in Listing 8.7:<br />

LISTING 8.7<br />

CircleWithStaticMembers.java<br />

1 public class CircleWithStaticMembers {<br />

2 /** The radius of the circle */<br />

3 double radius;<br />

4<br />

5 /** The number of objects created */<br />

6 static int numberOfObjects = 0;<br />

7<br />

8 /** Construct a circle with radius 1 */<br />

9 CircleWithStaticMembers() {<br />

10 radius = 1;<br />

11 numberOfObjects++;<br />

12 }<br />

13<br />

14 /** Construct a circle with a specified radius */<br />

15 CircleWithStaticMembers(double newRadius) {<br />

16 radius = newRadius;<br />

17 numberOfObjects++;<br />

18 }<br />

19<br />

20 /** Return numberOfObjects */<br />

21 static int getNumberOfObjects() {<br />

22 return numberOfObjects;<br />

23 }<br />

24<br />

static variable<br />

increase by 1<br />

increase by 1<br />

static method

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!