Java Reference
In-Depth Information
Itmightseempointlesstogotoallthisbotherwhenyoucouldsimplyomit private
and access the name field directly. However, suppose you are told to introduce a new
constructorthattakesseparatefirstandlastnameargumentsandnewmethodsthatset/
gettheemployee'sfirstandlastnamesintothisclass.Furthermore,supposethatithas
beendeterminedthatthefirstandlastnameswillbeaccessedmoreoftenthantheentire
name. Listing 2-14 reveals these changes.
Listing 2-14. Revising implementation without affecting existing interface
public class Employee
{
private String firstName;
private String lastName;
public Employee(String name)
{
setName(name);
}
public Employee(String firstName, String lastName)
{
setName(firstName+" "+lastName);
}
public void setName(String name)
{
// Assume that the first and last names are separated
by a
// single space character. indexOf() locates a char-
acter in a
// string; substring() returns a portion of a string.
setFirstName(name.substring(0, name.indexOf(' ')));
setLastName(name.substring(name.indexOf(' ')+1));
}
public String getName()
{
return getFirstName()+" "+getLastName();
}
public void setFirstName(String empFirstName)
{
 
Search WWH ::




Custom Search