Methods setCourseName and getCourseName

Method setCourseName (lines 10–13) does not return any data when it completes its task, so its return type is void. The method receives one parameter—name—which represents the course name that will be passed to the method as an argument. Line 12 assigns name to instance variable courseName.

Method getCourseName (lines 16–19) returns a particular GradeBook object’s courseName. The method has an empty parameter list, so it does not require additional information to perform its task. The method specifies that it returns a String—this is the method’s return type. When a method that specifies a return type other than void is called and completes its task, the method returns a result to its calling method. For example, when you go to an automated teller machine (ATM) and request your account balance, you expect the ATM to give you back a value that represents your balance. Similarly, when a statement calls method getCourseName on a GradeBook object, the statement expects to receive the GradeBook’s course name (in this case, a String, as specified in the method declaration’s return type).

The return statement in line 18 passes the value of instance variable courseName back to the statement that calls method getCourseName. Consider, method displayMessage’s line 27, which calls method getCourseName. When the value is returned, the statement in lines 26–27 uses that value to output the course name. Similarly, if you have a method square that returns the square of its argument, you’d expect the statement

int result = square( 2 );

to return 4 from method square and assign 4 to the variable result. If you have a method maximum that returns the largest of three integer arguments, you’d expect the statement

int biggest = maximum( 27, 114, 51 );

to return 114 from method maximum and assign 114 to variable biggest.

The statements in lines 12 and 18 each use courseName even though it was not declared in any of the methods. We can use courseName in GradeBook’s methods because courseName is an instance variable of the class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset