Accessor and Mutator Methods
Accessor and Mutator Methods
Accessor and Mutator Methods
I. Background
• Recall that there are two kinds of methods in the world - those
that return a value and those that do not - and that this
determines the way in which we call the method (see “Objects,
Classes, and Methods”)
• Mutator methods change the state of the object. (The state of the
object is determined by the values of the instance fields)
• Since every object created has its own copy of each of the
instance variables of the class, every Rectangle object “knows”
its own x, y, width, and height
• Assume that a Rectangle object called box has been created like
this:
Rectangle box = new Rectangle(5,10,20,30) ;
and that these variables have been declared:
double xValue ;
double yValue ;
double area ;
Then, when these statements are executed:
xValue = box.getX() ;
yValue = box.getY() ;
System.out.println( "The upper-left corner of the box is at ("
+ xValue + "," + yValue + ")” ) ;
System.out.println( "The box has an area of " +
box.getWidth() * box.getHeight() ) ;
the output will be:
The upper-left corner of the box is at (5,10)
The box has an area of 600
The above code shows again how to call methods that return a
value. Use the method call – object-name.method-name(args) –
in a Java statement. As shown, getX() and getY() are called
in assignment statements, and getWidth() and getHeight() are
called in a println statement