5.5. Defining and Using a Class

To put what you know about classes to use, you can use the Sphere class in an example.

You will be creating two source files. In a moment you'll create the file CreateSpheres.java, which will contain the definition of the CreateSpheres class that will have the method main() defined as a static method. As usual, this is where execution of the program starts. The other file will be the Sphere.java file, which contains the definition of the Sphere class that you have been assembling. The Sphere class definition should look like this:

class Sphere {
  static final double PI = 3.14;       // Class variable that has a fixed value
  static int count = 0;                // Class variable to count objects

  // Instance variables
  double radius;                       // Radius of a sphere

  double xCenter;                      // 3D coordinates
  double yCenter;                      // of the center
  double zCenter;                      // of a sphere
  // Class constructor
  Sphere(double theRadius, double x, double y, double z) {
    radius = theRadius;                // Set the radius

    // Set the coordinates of the center
    xCenter = x;
    yCenter = y;
    zCenter = z;
    ++count;                           // Update object count

  // Static method to report the number of objects created
static int getCount() {
    return count;                      // Return current object count

  // Instance method to calculate volume
  double volume() {
    return 4.0/3.0*PI*radius*radius*radius;

Both files need to be in the same directory or folder—I suggest you name the directory CreateSpheres. Then copy or move the latest version of Sphere.java to this directory.

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.