Java Reference
In-Depth Information
method as final prevents accidental modification of the object reference that is passed to the method, but it
does not prevent modification of the object itself.
Another important use for the final keyword is for declaring classes or methods as final, and you learn
more about this in Chapter 6.
Defining Class Methods
You define a class method by adding the keyword static to its definition. For example, the class Sphere
could have a class method to return the value stored in the static variable count :
class Sphere {
// Class definition as before...
// 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 you want to be able to get at the count of the number
of objects that exist even when it is zero. You can amend the Sphere.java file to include the definition of
getCount() .
NOTE Remember that you cannot directly refer to any of the instance variables in the class
within a static method. This is because a static method can 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
}
Search WWH ::




Custom Search