Start of Tutorial > Start of Trail > Start of Lesson | Search |
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 ofString
's accessor methods to obtain information about thesource
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
usesString
'slength
accessor method to obtain the length of theString
source
.Note thatint len = source.length();reverseIt
doesn't care ifString
maintains its length attribute as an integer, as a floating point number, or even ifString
computes its length on the fly.reverseIt
simply relies on the public interface of thelength
method, which returns the length of theString
as an integer. That's allreverseIt
needs to know.Second,
reverseIt
uses thecharAt
accessor, which returns the character at the position specified in the parameter.The character returned bysource.charAt(i)charAt
is then appended to theStringBuffer
dest
. Since the loop variablei
begins at the end ofsource
and proceeds backwards over the string, the characters are appended in reverse order to theStringBuffer
, thereby reversing the string.
In addition tolength
andcharAt
,String
supports a number of other accessor methods that provide access to substrings and the indices of specific characters in theString
.StringBuffer
has its own set of similar accessor methods.
Start of Tutorial > Start of Trail > Start of Lesson | Search |