Java Reference
In-Depth Information
is being applied. The code in the method then relates to the specific members of the object re-
ferred to by this .
You have seen that there are four different potential sources of data available to you when you write the
code for a method:
• Arguments passed to the method, which you refer to by using the parameter names
• Data members, both instance variables and class variables, which you refer to by their names
• Local variables that you declare in the body of the method
• Values that are returned by other methods that are called from within the method
The names of variables that are declared within a method are local to the method. You can use a name
for a local variable or a parameter in a method that is the same as that of an instance variable. If you find it
necessary or convenient to do this then you must use the name this when you refer to the data member of
the class from within the method. The variable name by itself always refers to the variable that is local to
the method, not the instance variable.
For example, suppose you want to add a method to change the radius of a Sphere object to a new radius
value that is passed as an argument. You 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. No confusion in the duplication of names exists here. It is clear that you are
receiving a radius value as a parameter with the name radius and storing it in the radius variable for the
class object.
Initializing Data Members
You have seen how you were able to supply an initial value for the static members PI and count in the
Sphere class with the following 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...
}
You 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
Search WWH ::




Custom Search