Trail: Essential Java Classes
|
Lesson: The String and StringBuffer Classes
|
|
Accessor Methods
An object's instance variables are encapsulated within the object,
hidden inside, safe from inspection or manipulation by other objects. With certain
well-defined exceptions, the object's methods are the only means
by which other objects can inspect or alter an object's instance variables.
Encapsulation of an object's data protects the object from
corruption by other objects and conceals an object's implementation
details from outsiders.
This encapsulation of data behind an object's methods is one of the
cornerstones of object-oriented programming.
Methods used to obtain information about an object are known as
accessor methods.
The reverseIt method uses two of String's
accessor methods to obtain information about the source string.
class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--) {
dest.append(source.charAt(i));
}
return dest.toString();
}
}
First, reverseIt uses String's
length accessor method to obtain the length of the String source.
int len = source.length();
Note that reverseIt doesn't care if String maintains its
length attribute as an integer, as a floating point number, or even if String
computes its length on the fly. reverseIt simply relies on the
public interface of the length method, which returns the length
of the String as an integer. That's all reverseIt needs
to know.
Second, reverseIt uses the
charAt )
accessor, which returns the character
at the position specified in the parameter.
source.charAt(i)
The character returned by charAt is then appended to the
StringBuffer dest. Since the loop variable i
begins at the end of source and proceeds backwards over
the string, the characters are appended in reverse order to the StringBuffer,
thereby reversing the string.
In addition to length and charAt, String
supports a number of other accessor methods that provide access
to substrings and the indices of specific characters in the String.
StringBuffer has its own set of similar accessor methods.
|