Java Reference
In-Depth Information
of a specific circle. Each Circle object can have a radius independent of all other
Circle objects.
Inside a class definition, instance fields are referred to by name alone. You can see
an example of this if you look at the method body of the circumference() instance
method. In code outside the class, the name of an instance method must be prefixed
with a reference to the object that contains it. For example, if the variable c holds a
reference to a Circle object, we use the expression c.r to refer to the radius of that
circle:
Circle c = new Circle (); // Create a Circle object; store a ref in c
c . r = 2.0 ; // Assign a value to its instance field r
Circle d = new Circle (); // Create a different Circle object
d . r = c . r * 2 ; // Make this one twice as big
Instance fields are key to object-oriented programming. Instance fields hold the
state of an object; the values of those fields make one object distinct from another.
Instance Methods
An instance method operates on a specific instance of a class (an object), and any
method not declared with the static keyword is automatically an instance method.
Instance methods are the feature that makes object-oriented programming start to
get interesting. The Circle class defined in Example 3-1 contains two instance
methods, area() and circumference() , that compute and return the area and cir‐
cumference of the circle represented by a given Circle object.
To use an instance method from outside the class in which it is defined, we must
prefix it with a reference to the instance that is to be operated on. For example:
// Create a Circle object; store in variable c
Circle c = new Circle ();
c . r = 2.0 ; // Set an instance field of the object
double a = c . area (); // Invoke an instance method of the object
This is why it is called object-oriented programming; the
object is the focus here, not the function call.
From within an instance method, we naturally have access to all the instance fields
that belong to the object the method was called on. Recall that an object is often best
considered to be a bundle containing state (represented as the fields of the object),
and behavior (the methods to act on that state).
All instance methods are implemented using an implicit parameter not shown in
the method signature. The implicit argument is named this ; it holds a reference to
Search WWH ::




Custom Search