Java Reference
In-Depth Information
2.21
Calling methods
The getLoginName method illustrates a new feature that is worth exploring:
public String getLoginName()
{
return name.substring(0,4) +
id.substring(0,3);
}
We are seeing two things in action here:
Calling a method on another object, where the method returns a result.
Using the value returned as a result as part of an expression.
Both name and id are String objects, and the String class has a method, substring , with
the following header:
/**
* Return a new string containing the characters from
* beginIndex to (endIndex-1) from this string.
*/
public String substring(int beginIndex, int endIndex)
An index value of zero represents the first character of a string, so getLoginName takes the
first four characters of the name string and the first three characters of the id string and then
concatenates them together to form a new string. This new string is returned as the method's re-
sult. For instance, if name is the string "Leonardo da Vinci" and id is the string "468366" ,
then the string "Leon468" would be returned by this method.
We will learn more about method calling between objects in Chapter 3.
Exercise 2.74 Draw a picture of the form shown in Figure 2.3, representing the initial state
of a Student object following its construction, with the following actual parameter values:
new Student("Benjamin Jonson", "738321")
Exercise 2.75 What would be returned by getLoginName for a student with name
"Henry Moore" and id "557214" ?
Exercise 2.76 Create a Student with name "djb" and id "859012" . What happens
when getLoginName is called on this student? Why do you think this is?
 
Search WWH ::




Custom Search