public class Point {
private int _x;
private int _y;
// Use static pointCount variable to track number of Point objects created:
private static int pointCount = 0;
// Constructors: static pointCount gets incremented in every constructor:
public Point( int x, int y ) {
setX( x );
setY( y );
pointCount++;
}
public Point() {
pointCount++;
}
...
...
// Instance methods can access static variables
public int getPointCount() {
return pointCount;
}
public class Rectangle {
private Point _point;
private int _width;
private int _height;
// Use static rectangleCount variable to track number of Rectangle objects
// created:
private static int rectangleCount = 0;
// Constructors: static rectangleCount gets incremented in every
// constructor:
public Rectangle( int point_x, int point_y, int width, int height )
{
_point = new Point( point_x, point_y );
// Must call Point class constructor to create _point
setWidth( width );
setHeight( height );
rectangleCount++;
}
...
...
// Instance methods can access static variables
public int getRectangleCount() {
return rectangleCount;
}
// Use Point class static pointCount variable:
System.out.println( box.getPoint().getPointCount() +
" points so far." );
// Use Rectangle class static rectangleCount variable:
System.out.println( box.getRectangleCount() +
" rectangles so far." );
public class Point {
...
private static int pointCount = 0;
...
...
// static version of getPointCount:
public static int sgetPointCount() {
return pointCount;
}
...
}
public class TestRectangle {
...
...
// Use Point class' static sgetPointCount method:
System.out.println( Point.sgetPointCount() + " points so far." );
...
...
}