Java Reference
In-Depth Information
For example, let us suppose we wanted to add a method to change the radius of a Sphere object to a
new radius value that is passed as an argument. We could code this as:
void changeRadius(double radius) {
// Change the instance variable to the argument value
this.radius = radius;
}
In the body of the changeRadius() method, this.radius refers to the instance variable, and radius
by itself refers to the parameter. There is no confusion in the duplication of names here. It is clear that we are
receiving a radius value as a parameter and storing it in the radius variable for the class object.
Initializing Data Members
We have seen how we were able to supply an initial value for the static members PI and count in the
Sphere class with the declaration:
class Sphere {
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Rest of the class...
}
We can also initialize ordinary non-static data members in the same way. For example:
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 = 5.0; // Radius of a sphere
double xCenter = 10.0; // 3D coordinates
double yCenter = 10.0; // of the center
double zCenter = 10.0; // of a sphere
// Rest of the class...
}
Now every object of type Sphere will start out with a radius of 5.0 and have the center at the point
10.0, 10.0, 10.0.
There are some things that can't be initialized with a single expression. If you had a large array as a data
member for example, that you wanted to initialize, with a range of values that required some kind of
calculation, this would be a job for an initialization block .
Search WWH ::




Custom Search