Java Reference
In-Depth Information
// 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;
}
}
The definition of the constructor is shaded above. We are accumulating quite a lot of code to define the
Sphere class, but as it's just an assembly of the pieces we have been adding, you should find it all quite
straightforward.
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. In our case we have four parameters, and each of the instance variables is initialized with
the value of the appropriate parameter. Here is a situation where we might have used the name radius
for the parameter, in which case we would need to use the keyword this to refer to the instance
variable of the same name. The last action of our constructor is to increment the class variable, count ,
by 1, so that count accumulates the total number of objects created.
The Default Constructor
If you don't define any constructors for a class, the compiler will supply a default constructor that has no
parameters and does nothing. Before we defined a constructor for our Sphere class, the compiler would
have supplied one defined like this:
Sphere() {
}
It has no parameters and has 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 will have fields with
their default values set.
Note that if you define a constructor of any kind for a class, the compiler will not supply a default
constructor. If you need one - and there are occasions when you do - you must define it explicitly.
Search WWH ::




Custom Search