Instance Variables, set Methods and get Methods

In Chapter 2, we declared all of an application's variables in the application's main method. Variables declared in the body of a particular method are known as local variables and can be used only in that method. When that method terminates, the values of its local variables are lost. Recall from Section 3.2 that an object has attributes that are carried with the object as it is used in a program. Such attributes exist before a method is called on an object and after the method completes execution.

A class normally consists of one or more methods that manipulate the attributes that belong to a particular object of the class. Attributes are represented as variables in a class declaration. Such variables are called fields and are declared inside a class declaration but outside the bodies of the class's method declarations. When each object of a class maintains its own copy of an attribute, the field that represents the attribute is also known as an instance variableeach object (instance) of the class has a separate instance of the variable in memory. The example in this section demonstrates a GradeBook class that contains a courseName instance variable to represent a particular GradeBook object's course name.

GradeBook Class with an Instance Variable, a set Method and a get Method

In our next application (Fig. 3.7Fig. 3.8), class GradeBook (Fig. 3.7) maintains the course name as an instance variable so that it can be used or modified at any time during an application's execution. The class contains three methodssetCourseName, getCourseName and displayMessage. Method setCourseName stores a course name in a GradeBook. Method getCourseName obtains a GradeBook's course name. Method displayMessagewhich now specifies no parametersstill displays a welcome message that includes the course name. However, as you will see, the method now obtains the course name by calling another method in the same classgetCourseName.

Figure 3.7. GradeBook class that contains a courseName instance variable.

1 // Fig. 3.7: GradeBook.java 2 // GradeBook class that contains a courseName instance variable 3 // and methods to set and get its value. 4 5 public class GradeBook 6 { 7 private String courseName; // course name for this GradeBook 8 9 // method to set the course name 10 public void setCourseName( String name ) 11 { 12 courseName = name; // store the course name 13 } // end method setCourseName 14 15 // method to retrieve the course name 16 public String getCourseName() 17 { 18 return courseName; 19 } // end method getCourseName 20 21 // display a welcome message to the GradeBook user 22 public void displayMessage() 23 { 24 // this statement calls getCourseName to get the 25 // name of the course this GradeBook represents 26 System.out.printf( "Welcome to the grade book for %s! ", 27 getCourseName() ); 28 } // end method displayMessage 29 30 } // end class GradeBook

A typical instructor teaches more than one course, each with its own course name. Line 7 declares that courseName is a variable of type String. Because the variable is declared in the body of the class (lines 630) but outside the bodies of the class's methods (lines 1013, 1619 and 2228), line 7 is a declaration for an instance variable. Every instance (i.e., object) of class GradeBook contains one copy of each instance variable. For example, if there are two GradeBook objects, each object has its own copy of courseName (one per object). A benefit of making courseName an instance variable is that all the methods of the class (in this case, GradeBook) can manipulate any instance variables that appear in the class (in this case, courseName).

Access Modifiers public and private

Most instance variable declarations are preceded with the private keyword (as in line 7). Like public, keyword private is an access modifier. Variables or methods declared with access modifier private are accessible only to methods of the class in which they are declared. Thus, variable courseName can be used only in methods setCourseName, getCourseName and displayMessage of (every object of) class GradeBook.

Software Engineering Observation 3.3

Precede every field and method declaration with an access modifier. As a rule of thumb, instance variables should be declared private and methods should be declared public. (We will see that it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class.)

Good Programming Practice 3.1

We prefer to list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class's fields anywhere in the class outside its method declarations, but scattering them tends to lead to hard-to-read code.

Good Programming Practice 3.2

Place a blank line between method declarations to separate the methods and enhance program readability.

Declaring instance variables with access modifier private is known as data hiding. When a program creates (instantiates) an object of class GradeBook, variable courseName is encapsulated (hidden) in the object and can be accessed only by methods of the object's class. In class GradeBook, methods setCourseName and getCourseName manipulate the instance variable courseName.

Method setCourseName (lines 1013) does not return any data when it completes its task, so its return type is void. The method receives one parameternamewhich 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 1619) 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 Stringthis is known as the method's return type. When a method that specifies a return type 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). If you have a method square that returns the square of its argument, you would expect the statement

int result = square( 2 );

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

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

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

Note that the statements at lines 12 and 18 each use courseName even though it was not declared in any of the methods. We can use courseName in the methods of class GradeBook because courseName is a field of the class. Also note that the order in which methods are declared in a class does not determine when they are called at execution time. So method getCourseName could be declared before method setCourseName.

Method displayMessage (lines 2228) does not return any data when it completes its task, so its return type is void. The method does not receive parameters, so the parameter list is empty. Lines 2627 output a welcome message that includes the value of instance variable courseName. Once again, we need to create an object of class GradeBook and call its methods before the welcome message can be displayed.

GradeBookTest Class That Demonstrates Class GradeBook

Class GradeBookTest (Fig. 3.8) creates one object of class GradeBook and demonstrates its methods. Line 11 creates a Scanner that will be used to obtain a course name from the user. Line 14 creates a GradeBook object and assigns it to local variable myGradeBook of type GradeBook. Lines 1718 display the initial course name calling the object's getCourseName method. Note that the first line of the output shows the name "null." Unlike local variables, which are not automatically initialized, every field has a default initial valuea value provided by Java when the programmer does not specify the field's initial value. Thus, fields are not required to be explicitly initialized before they are used in a programunless they must be initialized to values other than their default values. The default value for a field of type String (like courseName in this example) is null, which we say more about in Section 3.6.

Figure 3.8. Creating and manipulating a GradeBook object.

(This item is displayed on page 95 in the print version)

1 // Fig. 3.8: GradeBookTest.java 2 // Create and manipulate a GradeBook object. 3 import java.util.Scanner; // program uses Scanner 4 5 public class GradeBookTest 6 { 7 // main method begins program execution 8 public static void main( String args[] ) 9 { 10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in ); 12 13 // create a GradeBook object and assign it to myGradeBook 14 GradeBook myGradeBook = new GradeBook(); 15 16 // display initial value of courseName 17 System.out.printf( "Initial course name is: %s ", 18 myGradeBook.getCourseName() ); 19 20 // prompt for and read course name 21 System.out.println( "Please enter the course name:" ); 22 String theName = input.nextLine(); // read a line of text 23 myGradeBook.setCourseName( theName ); // set the course name 24 System.out.println(); // outputs a blank line 25 26 // display welcome message after specifying course name 27 myGradeBook.displayMessage(); 28 } // end main 29 30 } // end class GradeBookTest  

Initial course name is: null Please enter the course name: CS101 Introduction to Java Programming Welcome to the grade book for CS101 Introduction to Java Programming!  

Line 21 prompts the user to enter a course name. Local String variable theName (declared in line 22) is initialized with the course name entered by the user, which is returned by the call to the nextLine method of the Scanner object input. Line 23 calls object myGradeBook's setCourseName method and supplies theName as the method's argument. When the method is called, the argument's value is assigned to parameter name (line 10, Fig. 3.7) of method setCourseName (lines 1013, Fig. 3.7). Then the parameter's value is assigned to instance variable courseName (line 12, Fig. 3.7). Line 24 (Fig. 3.8) skips a line in the output, then line 27 calls object myGradeBook's displayMessage method to display the welcome message containing the course name.

set and get Methods

A class's private fields can be manipulated only by methods of that class. So a client of an objectthat is, any class that calls the object's methodscalls the class's public methods to manipulate the private fields of an object of the class. This is why the statements in method main (Fig. 3.8) call methods setCourseName, getCourseName and displayMessage on a GradeBook object. Classes often provide public methods to allow clients of the class to set (i.e., assign values to) or get (i.e., obtain the values of) private instance variables. The names of these methods need not begin with set or get, but this naming convention is highly recommended in Java and is required for special Java software components called JavaBeans that can simplify programming in many Java integrated development environments (IDEs). The method that sets instance variable courseName in this example is called setCourseName, and the method that gets the value of instance variable courseName is called getCourseName.

GradeBook's UML Class Diagram with an Instance Variable and set and get Methods

Figure 3.9 contains an updated UML class diagram for the version of class GradeBook in Fig. 3.7. This diagram models class GradeBook's instance variable courseName as an attribute in the middle compartment of the class. The UML represents instance variables as attributes by listing the attribute name, followed by a colon and the attribute type. The UML type of attribute courseName is String. Instance variable courseName is private in Java, so the class diagram lists a minus sign () in front of the corresponding attribute's name. Class GradeBook contains three public methods, so the class diagram lists three operations in the third compartment. Recall that the plus (+) sign before each operation name indicates that the operation is public. Operation setCourseName has a String parameter called name. The UML indicates the return type of an operation by placing a colon and the return type after the parentheses following the operation name. Method getCourseName of class GradeBook (Fig. 3.7) has a String return type in Java, so the class diagram shows a String return type in the UML. Note that operations setCourseName and displayMessage do not return values (i.e., they return void), so the UML class diagram does not specify a return type after the parentheses of these operations.

Figure 3.9. UML class diagram indicating that class GradeBook has a courseName attribute of UML type String and three operationssetCourseName (with a name parameter of UML type String), getCourseName (returns UML type String) and displayMessage.

Категории