Java Reference
In-Depth Information
// 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;
}
}
The definition of the constructor is in boldface type in the preceding code. As you can see, the constructor
has the same name as the class and has no return type specified. A constructor can have any number of
parameters, including none. The default constructor has no parameters, as is indicated by its alternative de-
scription — the no-arg constructor. In this case the Sphere class constructor has four parameters, and each
of the instance variables is initialized with the value of the appropriate parameter. Here's a situation where
you might have used the name radius for the parameter, in which case you would need to use the keyword
this to refer to the instance variable of the same name. The last action of the constructor is to increment the
class variable count by 1, so that count accumulates the total number of objects created.
The Default Constructor
As I said, if you don't define any constructors for a class, the compiler supplies a default constructor that has
no parameters and does nothing. Before you defined a constructor for the Sphere class, the compiler would
have supplied one, defined like this:
Sphere() {
}
It has no parameters and no statements in its body so it does nothing — except enable you to create an
object of type Sphere , of course. The object created by the default constructor has fields with their default
values set. If you have defined any non-static initialization blocks within a class, they are executed each
time any constructor executes, immediately before the execution of the code in the body of the constructor.
Whenever you create an object, a constructor is called. When you have not defined any constructors for a
class, the default constructor is called each time you create an object of that class type.
Note that if you define a constructor of any kind for a class, the compiler does not supply a default con-
structor. If you still need a no-arg constructor — and you will find many occasions when you do — you
must define it explicitly in addition to the other constructors in the class.
Creating Objects of a Class
When you declare a variable of type Sphere with the following statement
Search WWH ::




Custom Search