Accessor+Methods

An **accessor method** is a method that is usually small, simple and provides the means for the state of an object to be accessed from other parts of a program. Although it introduces a new dependency, use of the methods are preferred to directly accessing state data because they provide an abstraction layer. For example, if a bank-account class provides a getBalance accessor method to retrieve the current balance (rather than directly accessing the balance data fields), then later revisions of the same code can implement a more complex mechanism balance retrieval (say, a database fetch) without the dependent code needing to be changed. An accessor method that changes the state of an object is called an update method, a modifier method, or a mutator method. Objects that provide such methods are considered mutable objects. The values returned are always in the form of integers or doubles.


 * Since all instance variables are private, they are not directly accessible in client classes. It is common to provide special public methods, called //accessors//, that return the values of instance variables.**

Ex: public int getHeight
 * Accessor Methods** are public methods that obtain information or **return** the values of instance variables. They are usually recognized as starting with the word "get." Accessors do **not** change the state of the variable.

code format="java5" public int getGPA(int grade1, int grade2, int grade3) {  return (double)(grade1+grade2+grade3)/3; }

code Other commonly seen accessor methods (these are self explanatory as well): getX; getY; getRotation; getSpeed; getTurn; getLocation;

For Strings, you also might want to access the index (or position) of a character or string within a String or the length of the String. In class, we learned how to access the position of characters and the length of the string using the methods ".indexOf" and ".length".

code format="java" String sound = "pika-chu";
 * .indexOf(some string to search for)** returns the index (position) of the beginning of the string searched for and returns -1 if not found. For example:

p i k a - c h u 0 1 2 3 4 5 6 7

sound.indexOf("chu"); //returns 5 sound.indexOf("p"); //returns 0 sound.indexOf("pikachu"); //returns -1 code code format="java" p i k a - c h u 0 1 2 3 4 5 6 7
 * .length** returns the number of characters in the String. For example:

sound.length; //returns 8 code