Java Reference
In-Depth Information
// Static method to report the number of objects created
static int getCount() {
return count; // Return current object count
}
}
This method needs to be a class method because we want to be able to get at the count of the number of
objects even when it is zero. You can amend the
Sphere.java
file to include the definition of
getCount()
.
Note that you cannot directly refer to any of the instance variables in the class within
a
static
method. This is because your
static
method may be executed when no
objects of the class have been created, and therefore no instance variables exist.
Accessing Class Data Members in a Method
An instance method can access any of the data members of the class, just by using the appropriate
name. Let's extend the class
Sphere
a little further by adding a method to calculate the volume of a
Sphere
object:
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
// 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;
}
// Plus the rest of the class definition...
}
You can see that the method
volume()
is an instance method because it is not declared as static. It has
no parameters but it does return a value of type
double
- the required volume. The method uses the
class variable
PI
and the instance variable
radius
in the volume calculation - this is the expression
4.0/3.0*PI*radius*radius*radius
(4/3)
r
3
in the return statement. The value that results from
this expression will be returned to the point where the method is called for a
Sphere
object.
π