56
5/21/2018 Chapter3:StartingwithJava-slidepdf.com http://slidepdf.com/reader/full/chapter-3-starting-with-java 1/56  TOPICS 3.1 Classes 3.2 More about Passing Arguments 3.3 Instance Fields and Methods 3.4 Constructors 3.5 A BankAccount Class 3.6 Classes Variables and Scope Classes 3.7 Packages and import Statements 3.8 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 3.9 Common Errors to Avoid CONCEPT: A class is the blueprint for an object. t specifies the attributes and methods that a particular type of object has. From the class, one or more objects may be created. TIP Section 1. 7 of Chapter 1 introduced you to the concepts and terms used in object oriented programming. f you have not read that section, you should go back and read it no w . Chapter 2 introduced you to the Java primitive data types: byte, short, int, long, char, float, double, and boolean. You use these data types to create variables, which are storage locations in the computer's memory. A primitive data type is called primitive because a variable created with a primitive data type has no built -in capabilities other than storing a value. Chapter 2 also introduced you to the String class, which allows you to create String objects. In addition to storing strings, String objects have numerous methods that perform operations on the strings they hold. s a review, let's look at an example. Consider the fol lowing statement : String cityName = Charleston ; For each string literal that appears in a Java program, a String object is created in memory to hold it . The string literal Charleston that appears in this statement causes a String

Chapter 3: Starting with Java

Embed Size (px)

DESCRIPTION

Computer Programming

Citation preview

  • ,

    TOPICS 3.1 Classes 3.2 More about Passing Arguments 3.3 Instance Fields and Methods 3.4 Constructors 3.5 A BankAccount Class 3.6 Classes, Variables, and Scope

    Classes

    3.7 Packages and import Statements 3.8 Focus on Object-Oriented Design:

    Finding the Classes and Their Responsibilities

    3.9 Common Errors to Avoid

    CONCEPT: A class is the blueprint for an object. It specifies the attributes and methods that a particular type of object has. From the class, one or more objects may be created.

    TIP: Section 1. 7 of Chapter 1 introduced you to the concepts and terms used in object-oriented programming. If you have not read that section, you should go back and read it now.

    Chapter 2 introduced you to the Java primitive data types: byte, short, int, long, char, float, double, and boolean. You use these data types to create variables, which are storage locations in the computer's memory. A primitive data type is called "primitive" because a variable created with a primitive data type has no built-in capabilities other than storing a value.

    Chapter 2 also introduced you to the String class, which allows you to create String objects. In addition to storing strings, String objects have numerous methods that perform operations on the strings they hold. As a review, let's look at an example. Consider the fol-lowing statement:

    String cityName = "Charleston";

    For each string literal that appears in a Java program, a String object is created in memory to hold it. The string literal "Charleston" that appears in this statement causes a String

    113

  • 114 Chapter 3 A First Look at Classes and Objects

    object to be created and initialized with the string "Charleston". This statement also declares a variable named cityName that references the String object. This means that the cityName variable holds the String object's memory address. This is illustrated in Figure 3-1.

    Figure 3-1 The cityName variable references a String object

    A String object The ci tyName variable holds the address of addresst-------~.I "Charleston"

    a String object.

    Assume that the same program has an int variable named stringSize. Look at the follow-ing statement.

    stringSize = cityName.length()i This statement calls the String class's length method, which returns the length of a string. The expression ci tyName . length ( ) returns the length of the string referenced by ci tyName. After this statement executes, the stringSize variable will contain the value 10, which is the length of the string "Charleston". ,

    As you saw in Chapter 2, the String class has other methods in addition to length. This illustrates one of the differences between an object created from a class and a variable created from a primitive data type. Class objects normally have methods that perform useful operations on their data. Primitive variables, however, only store data and have no methods. Any operations performed on a primitive variable must be written in code that is external to the variable.

    Classes and Instances Java is an object-oriented programming language. Because objects can be much more powerful than primitive variables, you will spend a great deal of time creating and working with them. Before an object can be created, it must be designed by a programmer. The pro-grammer determines the attributes and methods that are necessary, and then writes a class. A class is a collection of programming statements that specify the attributes and methods that a particular type of object may have. As mentioned in Chapter 1, you should think of a class as a "blueprint" that objects may be created from. A blueprint and the items that are created from the blueprint are not the same thing, how-ever. Think of the difference between a blueprint for a house, and an actual house that is built from the blueprint. The blueprint itself is not a house, but is a detailed description of a house. When we use the blueprint to build an actual house, we are building an instance of the house described by the blueprint. If we so desire, we can build several identical houses from the same blueprint. Each house is a separate instance of the house that is described by the blueprint.

    The cookie cutter metaphor is often used to describe classes and objects. Although a cookie cutter itself is not a cookie, it describes a cookie. The cookie cutter can be used to make several cookies, as shown in Figure 3-2. Think of a class as a cookie cutter and the objects created from the class as cookies.

  • \

    3.1 Classes 115

    Figure 3-2 The cookie cutter metaphor

    Cookie cutter

    Cookies

    Think of a class as a cookie cutter and objects as the cookies.

    So, a class is not an object, but a description of an object. Once a class has been written, you can use the class to create as many objects as needed. Each object is considered an instance of the class. All of the objects that are created from the same class will have the attributes and methods described by the class. For example, we can create several objects from the String class, as demonstrated with the following code:

    String person = "Jenny"; String pet = "Fido" ;

    String favoriteColor = "Blue";

    As illustrated in Figure 3-3, this code creates three String objects in memory, which are referenced by the person, pet, and favoriteColor variables.

    Figure 3-3 Three variables referencing three String objects

    The person variable holds the address of

    a String object.

    The pet variable holds the address of

    a String object.

    ThefavoriteColor variable holds the

    address of a String object.

    A String object laddresst-I---------I "Jenny" I

    A String object I addresst-I------___ I "F ido " I

    A String object laddresst-I---------I "Blue" I

  • 116 Chapter 3 A First Look at Classes and Objects

    Although each of the three String objects holds different data, they are all identical in design. For example, we can call the length method for each of the objects as shown here.

    stringSize = person.length(); stringSize = pet.length(); stringSize = favoriteColor . length();

    Because each of the three objects is an instance of the String class, each has the attributes and methods specified by the String class.

    Building a Simple Class Step by Step In this section we will write a class named Rectangle. Each object that is created from the Rectangle class will be able to hold data about a rectangle. Specifically, a Rectangle object will have the following attributes:

    length. The length attribute will hold the rectangle's length. width. The width attribute will hold the rectangle's width.

    The Rectangle class will also have the following methods:

    setLength. The setLength method will store a value in the length attribute. setWidth. The setWidth method will store a value in the width attribute. getLength. The getLength method will return the value in the length attribute. getWidth. The getWidth method will return the value in the width attribute. getArea. The getArea method will return the area of the rectangle, which is the result

    of its length multiplied by its width.

    When designing a class it is often helpful to draw a UML diagram. UML stands for Unified Modeling Language. It provides a set of standard diagrams for graphically depicting object-oriented systems. Figure 3-4 shows the general layout of a UML diagram for a class. Notice that the diagram is a box that is divided into three sections. The top section is where you write the name of the class. The middle section holds a list of the class's attributes. The bottom section holds a list of the class's methods.

    Figure 3-4 General layout of a UML diagram for a class

    Class name goes here -r-----------------~

    Attributes are listed here -

    Methods are listed here -

    Following this layout, Figure 3-5 shows a UML diagram for our Rectangle class. Throughout this book we frequently use UML diagrams to illustrate classes.

    ,

  • \

    3.1 Classes 117

    Figure 3-5 UML diagram for the Rectangle class

    Rectangle

    length width

    setLengthO setWidthO getLengthO getWidthO getAreaO

    Writing the Code for a Class Now that we have identified the attributes and methods that we want the Rectangle class to have, let's write the Java code. First, we use an editor to create a new file named Rectangle.java. In the Rectangle.java file we will start by writing a general class "skeleton" as follows.

    public c l ass Rectangle {

    The key word public, which appears in the first line, is an access specifier. An access specifier indicates how the class may be accessed. The public access specifier indicates that the class will be publicly available to code that is written outside the Rectangle.java file . Almost all of the classes that we will write in this book will be public.

    Following the access specifier is the key word c l as s , followed by Rec t ang l e , which is the name of the class. On the next line an opening brace appears, which is followed by a clos-ing brace. The contents of the class, which are the attributes and methods, will be written inside these braces. The general format of a class definition is:

    AccessSpecifier c l ass Name {

    Members

    In general terms, the attributes and methods that belong to a class are referred to as the class's members.

    Writing the Code for the Class Attributes Let's continue writing our Rectang l e class by filling in the code for some of its members. First we will write the code for the class's two attributes, length and wi dth . We will use variables of the doub l e data type for these attributes. The new lines of code are shown in bold, as follows.

  • 118 Chapter 3 A First Look at Classes and Objects

    public class Rectangle {

    private double length; private double width;

    These two lines of code that we have added declare the variables length and width. Notice that both declarations begin with the key word private, preceding the data type. The key word private is an access specifier. It indicates that these variables may not be accessed by statements outside the class.

    Recall from our discussion in Chapter 1 on object-oriented programming that an object can perform data hiding, which means that critical data stored inside the object is protected from code outside the object. In Java, a class's private members are hidden and can be accessed only by methods that are members of the same class. When an object's internal data is hidden from outside code and access to that data is restricted to the object's meth-ods, the data is protected from accidental corruption. It is a common practice in object-oriented programming to make all of a class's attributes private and to provide access to those attributes through methods.

    When writing classes, you will primarily use the private and public access specifiers for , class members. Table 3-1 summarizes these access specifiers.

    Table 3-1 Summary of the private and public Access Specifiers for Class Members

    Access Specifier Description private When the pri vate access specifier is applied to a class member, the

    member cannot be accessed by code outside the class. The member can be accessed only by methods that are members of the same class.

    public When the public access specifier is applied to a class member, the mem-ber can be accessed by code inside the class or outside.

    You can optionally initialize an attribute with a value. For example, the following statements declare length and width, and initialize them with the values 10 and 12 respectively:

    private double length = 10; private double width = 12;

    If you do not provide initialization values for numeric attributes, they will be automati-cally initialized with O. We will discuss default initialization in greater detail later in this chapter.

    Before moving on, we should introduce the term field. In Java, a field is a class member that holds data. In our Rectangle class, the length and width variables are both fields.

    TIP: We have referred to length and width both as attributes and fields. Don't let this confuse you. The term "attribute" is a generic OOP term that refers to an item of data held by an object. The term "field" is a Java-specific term that refers to a member of a class that holds data. In Java, you use fields as attributes.

  • \

    3.1 Classes 119

    Writing the setLength Method Now we will begin writing the class methods. We will start with the setLength method. This method will allow code outside the class to store a value in the length field. Code Listing 3-1 shows the Rectangle class at this stage of its development. The setLength method is in lines 16 through 19. (This file is stored in the student source code folder Chapter 03\Rectangle Class Phase 1.)

    Code Listing 3-1 (Rectangle. java)

    1 2 3 4 5 6 7 8 9

    10 11 12 13 14 15 16 17 18 19 20

    /** * Rectangle class, Phase 1 * Under Construction! */

    public class Rectangle {

    private double length; private double width;

    /** * The setLength method accepts an argument * that is stored in the length field. */

    public void setLength(double len) {

    length = len;

    In lines 11 through 14 we write a block comment that gives a brief description of the method. It's important to always write comments that describe a class's methods so that in the future, anyone reading the code will better understand it. The definition of the method appears after the block comment in lines 16 through 19. The first line of the method defini-tion, which appears in line 16, is known as the method header. It appears as:

    public void setLength(double len) The method header has several parts. Let's look at each one.

    pUblic. The key word public is an access specifier. It indicates that the method may be called by statements outside the class.

    void. This is the method's return type. The key word void indicates that the method returns no data to the statement that called it.

    setLength. This is the name of the method. (double len). This is the declaration of a parameter variable. A parameter variable

    holds the value of an argument that is passed to the method. The parameter variable's name is len, and it is of the double data type.

  • 120 Chapter 3 A First Look at Classes and Objects

    Figure 3-6 labels each part of the header for the setLength method.

    Figure 3-6 Header for the setLength method

    Return type

    Access spec~ier j public void

    Method name ~

    setLength(double I I

    len) I

    Parameter variable declaration

    After the header, the body of the method appears inside a set of braces:

    length len;

    This method has only one statement, which assigns the value of len to the length field. When the method executes, the len parameter variable will hold the value of an argument that is passed to the method. That value is assigned to the length field.

    Before adding the other methods to the class, it might help if we demonstrate how the setLength method works. First, notice that the Rectangle class does not have a main method. This class is not a complete program, but is a blueprint that Rectangle objects may be created from. Other programs will use the Rectangle class to create objects. The programs that create and use these objects will have their own main methods. We can dem-onstrate the class's setLength method by saving the current contents of the Rectangle.java file and then creating the program shown in Code Listing 3-2. (This file is also stored in the student source code folder Chapter 03\Rectangle Class Phase 1.)

    Code Listing 3-2 (LengthDerno.java)

    1 /** 2 * This program demonstrates the Rectangle class's 3 * setLength method . 4 * / 5 6 public class LengthDemo 7 { 8 public static void main(String[] args) 9 {

    10 Rectangle box = new Rectangle(); 11 12 System.out.println("Sending the value 10.0 to " l3 + "the setLength method."); 14 box.setLength(10.0); 15 System.out.println("Done."); 16 } 17 }

    ,

  • \

    3.1 Classes 121

    The program in Code Listing 3-2 must be saved as LengthDemo.java in the same folder or directory as the file Rectangle.java. The following command can then be used with the Sun JDK to compile the program:

    javac LengthDemo.java When the compiler reads the source code for LengthDemo.java and sees that a class named Rectangle is being used, it looks in the current folder or directory for the file Rectangle. class. That file does not exist, however, because we have not yet compiled Rectangle.java. So, the compiler searches for the file Rectangle.java and compiles it. This creates the file Rectangle. class, which makes the Rectangle class available. The compiler then finishes compiling LengthDemo.java. The resulting LengthDemo.class file may be executed with the following command:

    java LengthDemo The output of the program is as follows.

    Program Output Sending the value 10 . 0 to the setLength method . Done.

    Let's look at each statement in this program's main method. In line 10 the program uses the following statement to create a Rectangle class object and associate it with a variable:

    Rectangle box = new Rectangle(); Let's dissect the statement into two p'arts. The first part of the statement,

    Rectangle box

    declares a variable named box. The data type of the variable is Rectangle. (Because the word Rectangle is not the name of a primitive data type, Java assumes it to be the name of a class.) Recall from Chapter 2 that a variable of a class type is a reference variable, and it holds the memory address of an object. When a reference variable holds an object's memory address, it is said that the variable references the object. So, the variable box will be used to reference a Rectangle object. The second part of the statement is:

    = new Rectangle(); This part of the statement uses the key word new, which creates an object in memory. After the word new, the name of a class followed by a set of parentheses appears. This specifies the class that the object should be created from. In this case, an object of the Rectangle class is created. The memory address of the object is then assigned (by the = operator) to the variable box. After the statement executes, the variable box will reference the object that was created in memory. This is illustrated in Figure 3-7.

    Figure 3-7 The box variable references a Rectangle class object

    The box variable holds the address of a Rectangle object.

    A Rectangle object length:~ width: B I addresst-I------... I

  • 122 Chapter 3 A First Look at Classes and Objects

    Notice that Figure 3-7 shows the Rectangle object's length and width fields set to O. All of a class's numeric fields are initialized to 0 by default.

    TIP: The parentheses in this statement are required. It would be an error to write the statement as:

    Rectangle box = new Rectangle ; II ERROR! !

    Lines 12 and 13 call the println method to display a message on the screen:

    System.out.println("Sending the value 10 .0 to " + "the setLength method .");

    Line 14 calls the box object's setLength method. As you have already seen from our exam-ples with the String class, you use the dot operator (a period) to access the members of a class object. Recall from Chapter 2 that the general form of a method call is

    I refvariable .methOd(arguments ... ) I

    where ref Variable is the name of a variable that references an object, method is the name of a method, and arguments . .. is zero or more arguments that are passed to the method. , An argument is a value that is passed into a method. Here is the statement in line 14 that calls the setLength method:

    box.setLength(10.0); This statement passes the argument 10.0 to the setLength method. When the method executes, the value 10.0 is copied into the len parameter variable. This is illustrated in Figure 3-8.

    Figure 3-8 The argument 10.0 is copied into the len parameter variable

    box.setLength(10.0) I

    l public void setLength(double len) {

    length = len ; }

    In the setLength method, the parameter variable len contains the value 10.0. The method assigns the value of len to the length field and then terminates. Figure 3-9 shows the state of the box object after the method executes.

    Figure 3-9 The state of the box object after the setLength method executes

    The box variable holds the address of a Rectangle object.

    I address 11--------.-A Rectangle object

    length:~ width:~

  • \

    3.1 Classes 123

    When passing an argument to a method, the argument's data type must be compatible with the parameter variable's data type. Otherwise, an error will occur. For example, the len parameter in the setLength method is a double variable. You cannot pass an argument that cannot be automatically converted to the doub l e data type. So, the following statement would cause an error because the argument is a string:

    box.setLength("10.0"); // ERROR!

    Writing the setwidth Method Now that we've seen how the setLength method works, let's add the setWidth method to the Rectangle class. The setWidth method is similar to setLength. It accepts an argument, which is assigned to the width field. Code Listing 3-3 shows the updated Rectangle class. The setWidth method is in lines 26 through 29. (This file is stored in the student source code folder Chapter 03\Rectangle Class Phase 2.)

    Code Listing 3-3 (Rectangle. java)

    1 /** 2 * Rectangle class, Phase 2 3 * Under Construction! 4 * / 5 6 public class Rectangle 7 { 8 private double length ; 9 private double width;

    10 11 /** 12 13 14 15

    * The setLength method accepts an argument * that is stored in the length field. */

    16 public void setLength(double len) 17 { 18 length = len; 19 } 20 21 /** 22 * The setWidth method accepts an argument 23 * that is stored in the width field. 24 */ 25 26 public void setwidth(double w) 27 { 28 width = w; 29 } 30

    The setWidth method has a parameter variable named w. When an argument is passed to the method, the argument's value is copied into the w variable. The value of the w variable

    __________________________________________________________________________________________________________ ~L

  • 124 Chapter 3 A First Look at Classes and Objects

    is then assigned to the width field . For example, assume that box references a Rectangle object and the following statement is executed:

    box.setWidth(20.0); After this statement executes, the box object's width field will be set to 20.0.

    Writing the getLength and getWidth Methods Because the length and width fields are private, we wrote the setLength and setWidth methods to allow code outside the Rectangle class to store values in the fields . We must also write methods that allow code outside the class to get the values that are stored in these fields. That's what the getLength and getWidth methods will do. The getLength method will return the value stored in the length field, and the getWidth method will return the value stored in the width field .

    Here is the code for the getLength method:

    public double getLength() {

    return length ;

    Notice that instead of the word void, the header uses the word double for the method's return type. This means that the method returns a value of the double data type. Also notice that no parameter variables are declared inside the parentheses. This means that the method does not accept arguments. The parentheses are still required, however.

    Inside the method, the following statement appears:

    return length ;

    This is called a return statement. The value that appears after the key word return is sent back to the statement that called the method. This statement sends the value that is stored in the length field. For example, assume that size is a double variable and that box refer-ences a Rectangle object, and the following statement is executed:

    size = box.getLength(); This statement assigns the value that is returned from the getLength method to the size variable. After this statement executes, the size variable will contain the same value as the box object's length field . This is illustrated in Figure 3-10.

    Figure 3-10 The value returned from getLength is assigned to size

    size = box.getLength();

    t ~UbliC double getLength() ~ return length, }

    ,

  • \

    3.1 Classes 125

    .A NOTE: No arguments are passed to the getLength method. You must still write the V parentheses, however, even when no arguments are passed.

    The getWidth method is similar to getLength. The code for the method follows.

    public double getwidth() {

    return width;

    This method returns the value that is stored in the width field. For example, assume that size is a double variable and that box references a Rectangle object, and the following statement is executed:

    size = box.getWidth(); This statement assigns the value that is returned from the getWidth method to the size variable. After this statement executes, the size variable will contain the same value as the box object's width field. Code Listing 3-4 shows the Rectangle class with all of the members we have discussed so far. The code for the getLength and getWidth methods is shown in lines 31 through 49. (This file is stored in the student source code folder Chapter 03\Rectangle Class Phase 3.)

    Code Listing 3-4 (Rectangle. java)

    1 2 3 4 5 6 7 8 9

    10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

    /** * Rectangle class, Phase 3 * Under Construction! */

    public class Rectangle {

    private double length; private double width;

    /** * The setLength method accepts an argument * that is stored in the length field . */

    public void setLength(double len) {

    length = len ;

    /** * The setwidth method accepts an argument * that is stored in the width field. */

    public void setWidth(double w) {

  • 126 Chapter 3 A First Look at Classes and Objects

    28 width = w; 29 30 31 /** 32 * The getLength method returns the value 33 * stored in the length field. 34 */ 35 36 public double getLength() 37 { 38 return length; 39 40 41 /** 42 * The getWidth method returns the value 43 * stored in the width field. 44 */ 45 46 public double getWidth() 47 { 48 return width; 49

    - - -

    Before continuing we should demonstrate how these methods work. Look at the program in Code Listing 3-5. (This file is also stored in the student source code folder Chapter 03\Rectangle Class Phase 3.)

    Code Listing 3-5 (LengthWidthDemo.java)

    1 /** 2 * This program demonstrates the Rectangle class's 3 * setLength, setwidth, getLength, and getWidth methods. 4 * / 5 6 public class LengthWidthDemo 7 { 8 public static void main(String[] args) 9 {

    10 Rectangle box = new Rectangle(); 11 12 box.setLength(10.0); 13 box.setwidth(20.0); 14 System.out.println("The box's length is " 15 + box.getLength()); 16 System. out. println ( "The box's width is " 17 + box.getWidth()); 18

    The box's length is 10.0 The box's width is 20.0

    ,

  • \

    3.1 Classes 127

    Let's take a closer look at the program. First, this program creates a Rectangle object, which is referenced by the box variable. Then the following statements, in lines 12 and 13, execute:

    box.setLength(10.0)i box.setwidth(20.0)i

    After these statements execute, the box object's length field is set to 10.0 and its width field is set to 20.0. The state of the object is shown in Figure 3-11.

    Figure 3-11 State of the box object

    The box variable holds the address of a Rectangle object.

    I addressll-------~ A Rectangle object

    length:~ width: ~

    Next, the following statement, in lines 14 and 15, executes:

    System. out. println ("The box's length is " + box.getLength())i

    This statement calls the box.getLength() method, which returns the value 10.0. The fol-lowing message is displayed on the screen:

    The box's length is 10.0

    Then the statement in lines 16 and 17 executes.

    System.out.println("The box's width is " + box.getWidth())i

    This statement calls the box. getWidth ( ) method, which returns the value 20.0. The follow-ing message is displayed on the screen:

    The box's width is 20.0

    Writing the getArea Method The last method we will write for the Rectangle class is getArea. This method returns the area of a rectangle, which is its length multiplied by its width. Here is the code for the getArea method:

    public double getArea() {

    return length * widthi

    This method returns the result of the mathematical expression length * width. For exam-ple, assume that area is a double variable and that box references a Rectangle object, and the following code is executed:

    box.setLength(10.0)i box.setwidth(20.0)i area = box.getArea()i

  • 128 Chapter 3 A First Look at Classes and Objects

    The last statement assigns the value that is returned from the getArea method to the area variable. After this statement executes, the area variable will contain the value 200.0.

    Code Listing 3-6 shows the Rectangle class with all of the members we have discussed so far. The getArea method appears in lines 56 through 59. (This file is stored in the student source code folder Chapter 03\Rectangle Class Phase 4.)

    Code Listing 3-6 (Rectangle. java)

    1 /** 2 * Rectangle class, Phase 4 3 * Under Construction! 4 * / 5 6 public class Rectangle 7 { 8 private double length; 9 private double width;

    10 11 12 13 14 15

    /** * The setLength method accepts an argument * that is stored in the length field . */

    16 public void setLength(double len) 17 { 18 length = len ; 19 20 21 /** 22 * The setWidth method accepts an argument 23 * that is stored in the width field. 24 * / 25 26 public void setWidth(double w) 27 { 28 width = w; 29 30 31 /** 32 * The getLength method returns the value 33 * stored in the length field. 34 * / 35 36 public double getLength() 37 { 38 return length ; 39 40 41 /** 42 * The getwidth method returns the value 43 * stored in the width field. 44 * / 45 46 public double getWidth()

    \

  • \

    47 48 49 50 51 1**

    return width;

    52 * The getArea method returns the value of the 53 * length field times the width field . 54 * I 55 56 public double getArea() 57 { 58 return length * width; 59 60

    3.1 Classes 129

    The program in Code Listing 3-7 demonstrates all the methods of the Rectangle class, including getArea. (This file is also stored in the student source code folder Chapter 03\Rectangle Class Phase 4.)

    Code Listing 3-7 (RectangleDemo.java)

    1 2 3 4 5 6 7 8 9

    10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

    1** * This program demonstrates the Rectangle class's * setLength, setWidth, getLength, getWidth, and * getArea methods. *1

    public class RectangleDemo {

    public static void main(String[] args) {

    II Create a Rectangle object. Rectangle box = new Rectangle();

    II Set the length to 10 and width to 20. box.setLength(10.0); box.setwidth(20.0);

    II Display the length, width, and area. System.out.println( "The box's length is "

    + box.getLength()); System.out.println( "The box's width is "

    + box.getWidth()); System. out. println ("The box's area is "

    + box.getArea());

    Program Output The box's length is 10.0 The box's width is 20.0 The box's area is 200.0

    i-

  • 130 Chapter 3 A First Look at Classes and Objects

    Accessor and Mutator Methods As mentioned earlier, it is a common practice to make all of a class's fields private and to provide public methods for accessing and changing those fields. This ensures that the object owning those fields is in control of all changes being made to them. A method that gets a value from a class's field but does not change it is known as an accessor method. A method that stores a value in a field or in some other way changes the value of a field is known as a mutator method. In the Rectangle class the methods getLength and getWidth are accessors, and the methods setLength and setWidth are mutators.

    Avoiding Stale Data Recall that the Rectangle class has the methods getLength, getWidth, and getArea. The getLength and getWidth methods return the values stored in fields, but the getArea method returns the result of a calculation. You might be wondering why the area of the rectangle is not stored in a field, like the length and the width. The area is not stored in a field because it could potentially become stale. When the value of an item is dependent on other data and that item is not updated when the other data is changed, it is said that the item has become stale. If the area of the rectangle were stored in a field, the value of the field would become incorrect as soon as either the length or width field changed. ,

    When designing a class, you should take care not to store in a field calculated data that could potentially become stale. Instead, provide a method that returns the result of the calculation.

    Showing Access Specification in UML Diagrams In Figure 3-5 we presented a UML diagram for the Rectangle class. The diagram listed all of the members of the class but did not indicate which members were private and which were public. In a UML diagram, you have the option to place a - character before a member name to indicate that it is private, or a + character to indicate that it is public. Figure 3-12 shows the UML diagram modified to include this notation.

    Figure 3-12 UML diagram for the Rectangle class

    Rectangle

    - length - width + setLengthO + setWidthO + getLengthO + getWidthO + getAreaO

    Data Type and Parameter Notation in UML Diagrams The Unified Modeling Language also provides notation that you can use to indicate the data types of fields, methods, and parameters. To indicate the data type of a field, place a colon followed by the name of the data type after the name of the field. For example, the

  • ,

    3.1 Classes 131

    length field in the Rectangle class is a double. It could be listed as follows in the UML diagram:

    - length : double

    The return type of a method can be listed in the same manner: After the method's name, place a colon followed by the return type. The Rectangle class's getLength method returns a double, so it could be listed as follows in the UML diagram:

    + getLength() : double

    Parameter variables and their data types may be listed inside a method's parentheses. For example, the Rectangle class's setLength method has a double parameter named len, so it could be listed as follows in the UML diagram:

    + setLength(len : double) : void Figure 3-13 shows a UML diagram for the Rectangle class with parameter and data type notation.

    Figure 3-13 UML diagram for the Rectangle class with parameter and data type notation

    Rectangle

    - length : double - width : double + setLength(len : double) : void + setWidth(w : double) : void + getLengthO : double + getWidthO : double + getAreaO : double

    Layout of Class Members Notice that in the Rectangle class, the field variables are declared first and then the meth-ods are defined. You are not required to write field declarations before the method defini-tions. In fact, some programmers prefer to write the definitions for the public methods first and then write the declarations for the private fields last. Regardless of which style you use, you should be consistent. In this book we always write the field declarations first, followed by the method definitions. Figure 3-14 shows this layout.

    Figure 3-14 Typical layout of class members

    public class ClassName {

    Field declarations

    Method definitions

  • 132 Chapter 3 A First Look at Classes and Objects

    ~ Checkpoint 3.1 In this chapter, we use the metaphor of a blueprint and houses that are created

    from the blueprint to describe classes and objects. In this metaphor, are classes the blueprint or the houses?

    3.2 We also use the metaphor of a cookie cutter and cookies that are made from the cookie cutter to describe classes and objects. In this metaphor, are objects the cookie cutter, or the cookies?

    3.3 When a variable is said to reference an object, what is actually stored in the variable? 3.4 A string literal, such as "Joe", causes what type of object to be created? 3.5 Look at the UML diagram in Figure 3-15 and answer the following questions.

    a) What is the name of the class? b) What are the attributes? c) What are the methods? d) What are the private members? e) What are the public members?

    Figure 3-15 UML diagram

    Car

    - make - yearModel

    + setMakeO + setYearModelO + getMakeO + getYearModelO

    3.6 Assume that limo is a variable that references an instance of the class depicted in Figure 3-15. Write a statement that calls setMake and passes the argument "Cadillac" .

    3.7 What does the key word new do? 3.8 What is a parameter variable? 3.9 What is an accessor? What is a mutator? 3.10 What is a stale data item?

    More about Passing Arguments

    CONCEPT: A method can have multiple parameter variables, allowing you to pass multiple arguments to the method. When an argument is passed to a method, it is passed by value. This means that the parameter variable holds a copy of the value passed to it. Changes made to the parameter variable do not affect the argument.

    ,

  • ,

    3.2 More about Passing Arguments 133

    Passing Multiple Arguments Often it is useful to pass more than one argument into a method. For example, the Rectangle class has two separate methods for setting the length and width fields: setLength and setWidth. Setting the length and width fields using these methods requires two method calls. We could add another method that accepts two arguments, one for the length and one for the width, making it possible to set both the length and the width fields with one method call. Here is such a method:

    public void set(double len, double w) {

    length = len; width = w;

    Two parameter variables, len and w, are declared inside the parentheses in the method header. This requires us to pass two arguments to the method when we call it. For example, assume that box references a Rectangle object and the following statement is executed.

    box.set(lO . O, 20 . 0); This statement passes the value 10.0 into the len parameter and the value 20.0 into the w parameter, as illustrated in Figure 3-16.

    Figure 3-16 Multiple arguments passed to the set method

    box . set(lO . O, 20 . 0); I ~I ------------~ public void ,et(double lln, double !, {

    length = len; width = w;

    Notice that the arguments are passed to the parameter variables in the order that they appear in the method call. In other words, the first argument is passed into the first parameter, and the second argument is passed into the second parameter. For example, the following method call would pass 15.0 into the len parameter and 30.0 into the w parameter:

    box.set(15 . 0, 30 . 0); The program in Code Listing 3-8 demonstrates passing two arguments to the set method. In this program, variables that are declared in the main method are passed as the arguments. (This file, along with a modified version of the Rectangle class, is stored in the student source code folder Chapter 03\Rectangle Class Phase 5.)

  • 134 Chapter 3 A First Look at Classes and Objects

    Code Listing 3-8 (MultipleArgs .j ava )

    1 import java.util.Scanner; II Needed for the Scanner class 2 3 1** 4 * This program demonstrates how to pass 5 * multiple arguments to a method . 6 *1 7 8 public class MultipleArgs 9 {

    10 public static void main(String[] args) 11 { 12 double boxLength, II To hold the box's length 13 boxwidth; II To hold the box's width 14 15 II Create a Scanner object for keyboard input . 16 Scanner keyboard = new Scanner(System. in) ; 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

    II Create a Rectangle object . Rectangle box = new Rectangle() ;

    II Get the box's length . System . out . print("What is the box ' s length? ") ; boxLength = keyboard . nextDouble() ;

    II Get the box's width . System. out. print ("What is the box ' s width? " ); boxWidth = keyboard . nextDouble( );

    II Pass boxLength and boxWidth to the set method . box . set(boxLength , boxWidth) ;

    II Display the box's length , width , and area . System. out . println("The box's length is "

    + box . getLength()) ; System . out.println("The box's width is "

    + box . getWidth()); System . out.println("The box's area is "

    + box.getArea()) ;

    Program Output with Example Input Shown in Bold What is the box's length? 10.0 [Enter] What is the box's width? 20.0 [Enter] The box's length is 10.0 The box's width is 20.0 The box's area is 200.0

    In the program, the user enters values that are stored in the boxLength and boxWidth vari-ables. The following statement, in line 30, calls the set method, passing the boxLength and boxwidth variables as arguments.

    box . set (boxLength, boxWidth) ;

    ,

  • ,

    3.3 Instance Fields and Methods 135

    When this statement executes, the value stored in the boxLength variable is passed into the len parameter, and the value stored in the boxWidth variable is passed into the w parameter.

    Arguments Are Passed by Value In Java, all arguments of the primitive data types are passed by value, which means that a copy of an argument's value is passed into a parameter variable. A method's parameter variables are separate and distinct from the arguments that are listed inside the parentheses of a method call. If a parameter variable is changed inside a method, it has no effect on the original argument.

    Instance Fields and Methods

    CONCEPT: Each instance of a class has its own set of fields, which are known as instance fields. You can create several instances of a class and store different values in each instance's fields. The methods that operate on an instance of a class are known as instance methods.

    The program in Code Listing 3-7 creates one instance of the Rectangle class. It is pos-sible to create many instances of the same class, each with its own data. For example, the RoomAreas.java program in Code Listing 3-9 creates three instances of the Rectangle class, referenced by the variables kitchen, bedroom, and den.

    Code Listing 3-9 (RoomAreas.java)

    1 2 3 4 5 6 7 8 9

    10 11 12 l3 14 15 16 17 18 19 20 21

    import java.util.Scanner; II Needed for the Scanner class

    1** * This program creates three instances of the * Rectangle class. *1

    public class RoomAreas {

    public static void main(String[] args) {

    double number, totalArea;

    II To hold numeric input II The total area of all rooms

    II Create a Scanner object for keyboard input . Scanner keyboard = new Scanner(System.in);

    II Create three Rectangle objects. Rectangle kitchen = new Rectangle(); Rectangle bedroom = new Rectangle(); Rectangle den = new Rectangle();

  • 136 Chapter 3 A First Look at Classes and Objects

    22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

    II Get and store the dimensions of the kitchen . System. out.print( "What is the kitchen ' s length ? " ) ; number = keyboard . nextDouble() ; kitchen . setLength(number) ; System . out.print ("What is the kitchen ' s width? " ); number = keyboard . nextDouble() ; kitchen . setWidth(number) ;

    I I Get and store the dimensions of the bedroom . System . out . print( "What is the bedroom ' s length? ") ; number = keyboard.nextDouble() ; bedroom . setLength(number) ; System . out . print("What is the bedroom's width? "); number = keyboard . nextDouble() ; bedroom . setWidth(number) ;

    II Get and store the dimensions of the den . System . out . print("What is the den's length? ") ; number = keyboard.nextDouble() ; den . setLength(number) ; System .out . print("What is the den ' s width? ") ; number = keyboard . nextDouble() ; den . setWidth(number);

    II Calculate the total area of the rooms . totalArea = kitchen . getArea() + bedroom . getArea( )

    + den . getArea() ;

    II Display the total area of the rooms . System. out.println( "The total area of the rooms is "

    + totalArea) ;

    Program Output with Example Input Shown in Bold What is the kitchen's length? 10 [Enter] What is the kitchen's wi dth? 14 [Enter] What is the bedroom's l ength? 15 [Enter] What is the bedroom's width? 12 [Enter] What is the den's length? 20 [Enter] What is the den's width? 30 [Enter] The total area of the rooms i s 920.0

    In the program, the code in lines 19 through 21 creates three objects, each an instance of the Rectangle class:

    Rectangle kitchen new Rectangle() ; Rectangle bedroom new Rectangle() ; Rectangle den = new Rectangle() ;

    ,

  • ,

    3.3 Instance Fields and Methods 137

    Figure 3-17 illustrates how the kitchen, bedroom, and den variables reference the objects.

    Figure 3-17 The kitchen, bedroom, and den variables reference Rectangle objects

    The ki tchen variable holds the address of a Rectangle object.

    The bedroom variable holds the address of a Rectangle object.

    The den variable holds the address of a Rectangle object.

    A Rectangle object

    6 . length:~ address 1------_1 width : ~

    A Rectangle object length:~

    width:~ 61-------1 A Rectangle object

    length:~ width:~ 61-------1

    In the example session with the program, the user enters 10 and 14 as the length and width of the kitchen, 15 and 12 as the length and width of the bedroom, and 20 and 30 as the length and width of the den. Figure 3-18 shows the states of the objects after these values are stored in them.

    Notice from Figure 3-18 that each instance of the Rectangle class has its own length and width variables. For this reason, the variables are known as instance variables, or instance fields. Every instance of a class has its own set of instance fields and can store its own values in those fields.

    Figure 3-18 States of the objects after data has been stored in them

    The ki tchen variable holds the address of a Rectangle object.

    The bedroom variable holds the address of a Rectangle object.

    The den variable holds the address of a Rectangle object.

    A Rectangle object length:~

    width:~ 6------~, A Rectangle object

    length:~ width:~ 6------~1

    A Rectangle object length:~

    width:~ 6------~,

  • ..

    138 Chapter 3 A First Look at Classes and Objects

    The methods that operate on an instance of a class are known as instance methods. All of the methods in the Rectangle class are instance methods because they perform operations on specific instances of the class. For example, look at line 26 in the RoomsAreas.java program:

    kitchen.setLength(number); This statement calls the setLength method which stores a value in the kitchen object's length field. Now look at line 34 in the same program.

    bedroom.setLength(number); This statement also calls the setLength method, but this time it stores a value in the bedroom object's length field. Likewise, line 42 calls the setLength method to store a value in the den object's length field:

    den.setLength(number); The setLength method stores a value in a specific instance of the Rectangle class. This is true of all of the methods that are members of the Rectangle class.

    ~ Checkpoint 3.11 Assume that rl and r2 are variables that reference Rectangle objects, and the fol-

    lowing statements are executed:

    rl.setLength(5.0); r2 . setLength(lO . O) ; rl . setWidth(20 .0); r2.setWidth(15.0);

    Fill in the boxes in Figure 3-19 that represent each object's length and width fields.

    Figure 3-19 Fill in the boxes for each field

    A Rectangle object length: D

    width: D rl !addreSSI-!---------;~1

    A Rectangle object length:D

    width: D r2 ! address!I-------... 1

    ,

  • ,

    3.4 Constructors 139

    Constructors

    CONCEPT: A constructor is a method that is automatically called when an object is created.

    A constructor is a method that is automatically called when an instance of a class is created. Constructors normally perform initialization or setup operations, such as storing initial values in instance fields .

    A constructor method has the same name as the class. For example, Code Listing 3-10 shows the first few lines of a new version of the Rectangle class. In this version of the class, a constructor has been added. (This file is stored in the student source code folder Chapter 03\Rectangle Class Phase 6. )

    Code Listing 3-1 0 (Rectangle . java)

    1 1** 2 * Rectangle class , Phase 6 3 *1 4 5 public class Rectangle 6 { 7 private double length; 8 private double width ; 9

    10 1** 11 * Constructor 12 * 1 13 14 15 16 17 18

    public Rectangle(double len , double w) {

    length = len ; width = w;

    ... The remainder of the class has not changed, and is not shown.

    This constructor accepts two arguments, which are passed into the len and w parameter variables. The parameter variables are then assigned to the length and width fields .

    Notice that the constructor's header doesn't specify a return type-not even void. This is because constructors are not executed by explicit function calls and cannot return a value. The method header for a constructor takes the following general form:

    AccessSpecifier ClassName(Arguments ... ) Here is an example statement that declares the variable box, creates a Rectangle object, and passes the values 7.0 and 14.0 to the constructor.

    Rectangle box = new Rectangle(7.0, 14 . 0); After this statement executes, box will reference a Rectangle object whose length field is set to 7.0 and whose width field is set to 14.0. The program in Code Listing 3-11 demonstrates

  • 140 Chapter 3 A First Look at Classes and Objects

    the Rectangle class constructor. (This file is stored in the student source code folder Chapter 03\Rectangle Class Phase 6.)

    Code Listing 3-11 (ConstructorDemo.java)

    1 1** 2 * This program demonstrates the Rectangle class's 3 * constructor. 4 *1 5 6 public class ConstructorDemo 7 { 8 public static void main(String[] args) 9 {

    10 Rectangle box = new Rectangle(5.0, 15.0); 11 12 13 14 15 16 17 18 19

    System.out.println("The box's length is " + box.getLength());

    System.out.println("The box's width is " + box.getwidth());

    System.out.println("The box's area is" + box.getArea());

    Program Output The box's length is 5.0 The box's width is 15.0 The box's area is 75.0

    The program in Code Listing 3-11 uses the new key word to create a Rectangle object as part of the box variable's declaration statement. Recall that the new key word can be used in a simple assignment statement as well. For example, the following statement can be used to declare box as a Rectangle variable.

    Rectangle box;

    Then, the following statement can be used to create a Rectangle object and pass the values 7.0 and 14.0 to its constructor.

    box = new Rectangle(7 . 0, 14 . 0) ; The RoomConstructor.java program in Code Listing 3-12 uses this technique. It is a modi-fication of the RoomAreas.java program presented earlier in this chapter. (This file is stored in the student source code folder Chapter 03\Rectangle Class Phase 6.)

    Code Listing 3-12 (RoomConstructor.java)

    1 import java . util . Scanner; II Needed for the Scanner class 2 3 1** 4 * This program creates three instances of the Rectangle 5 * class and passes arguments to the constructor.

    ,

  • ,

    6 7 8 9

    10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

    *1

    public class RoomConstructor {

    public static void main(String [] args) {

    double roomLength, roomwidth, totalArea;

    II To hold a room's length II To hold a room's width II To hold the total area

    II Declare Rectangle variables to reference II objects for the kitchen, bedroom, and den . Rectangle kitchen, bedroom, den;

    II Create a Scanner object for keyboard input . Scanner keyboard = new Scanner(System.in);

    II Get and store the dimensions of the kitchen. System . out.print ("What is the kitchen's length? "); roomLength = keyboard . nextDouble(); System.out.print("What is the kitchen's width? "); roomWidth = keyboard.nextDouble(); kitchen = new Rectangle (roomLength, roomWidth);

    II Get and store the dimensions of the bedroom. System.out.print("what is the bedroom's length? "); roomLength = keyboard.nextDouble(); System.out.print("What is the bedroom's width? "); roomWidth = keyboard.nextDouble(); bedroom = new Rectangle(roomLength, roomWidth);

    II Get and store the dimensions of the den. System. out. pr int ("What is the den's length? "); roomLength = keyboard.nextDouble(); System. out. pr int ("What is the den's width? "); roomWidth = keyboard.nextDouble(); den = new Rectangle(roomLength, roomWidth);

    II Calculate the total area of the rooms. totalArea = kitchen.getArea() + bedroom.getArea()

    + den . getArea ( ) ;

    II Display the total area of the rooms . System.out.println("The total area of the rooms is

    + totalArea);

    Program Output with Example Input Shown in Bold What is the kitchen's length? 10 [Enter] What is the kitchen's width? 14 [Enter] What is the bedroom's length? 15 [Enter] What is the bedroom's width? 12 [Enter] What is the den's length? 20 [Enter] What is the den's width? 30 [Enter] The total area of the rooms is 920.0

    3.4 Constructors 141

  • 142 Chapter 3 A First Look at Classes and Objects

    In the program, the following statement in line 18 declares kitchen, bedroom, and den as Rectangle variables:

    Rectangle kitchen, bedroom, den;

    These variables do not yet reference instances of the Rectangle class, however. Because these variables do not yet hold an object's address, they are uninitialized reference variables. These variables cannot be used until they reference objects. The following statement, which appears in line 28, creates a Rectangle object, passes the roomLength and roomWidth variables as arguments to the constructor, and assigns the object's address to the kitchen variable.

    kitchen = new Rectangle(roomLength, roomWidth); After this statement executes, the kitchen variable will reference the Rectangle object. Similar statements also appear later in the program that cause the bedroom and den variables to reference objects.

    The Default Constructor When an object is created, its constructor is always called. But what if we do not write a constructor in the object's class? If you do not write a constructor in a class, Java automati-cally provides one when the class is compiled. The constructor that Java provides is known as the default constructor. The default constructor doesn't accept arguments. It sets all of the class's numeric fields to 0, boolean fields to false, and char fields to the Unicode value O. If the object has any fields that are reference variables, the default constructor sets them to the special value null, which means that they do not reference anything.

    The only time that Java provides a default constructor is when you do not write your own constructor for a class. For example, at the beginning of this chapter we developed the Rectangle class without writing a constructor for it. When we compiled the class, the compiler generated a default constructor that set both the length and width fields to 0.0. Assume that the following code uses that version of the class to create a Rectangle object:

    II We wrote no constructor for the Rectangle class. Rectangle r = new Rectangle(); II Calls the default constructor

    When we created Rectangle objects using that version of the class, we did not pass any arguments to the default constructor, because the default constructor doesn't accept argu-ments.

    Later we added our own constructor to the class. The constructor that we added accepts arguments for the length and width fields. When we compiled the class at that point, Java did not provide a default constructor. The constructor that we added became the only constructor that the class had. When we create Rectangle objects with that version of the class, we must pass the length and width arguments to the constructor. Using that version of the class, the following statement would cause an error because we have not provided arguments for the constructor.

    II Now we wrote our own constructor for the Rectangle class . Rectangle box = new Rectangle(); II Error! Must now pass arguments.

    Because we have added our own constructor, which requires two arguments, the class no longer has a default constructor.

    ,

  • ,

    3.4 Constructors 143

    No-Arg Constructors A constructor that does not accept arguments is known as a no-arg constructor. The default constructor doesn't accept arguments, so it is considered a no-arg constructor. In addition, you can write your own no-arg constructor. For example, suppose we wrote the following constructor for the Rectangle class:

    public Rectangle() {

    length = 1. 0 ; width = 1.0;

    If we were using this constructor in our Rectangle class, we would not pass any arguments when creating a Rectangle object. The following code shows an example. After this code executes, the Rectangle object's length and width fields would both be set to 1.0.

    II Now we have written our own no-arg constructor. Rectangle r = new Rectangle(); II Calls the no-arg constructor

    Showing Constructors in a UML Diagram There is more than one accepted way of showing a class's constructor in a UML diagram. In this book, we simply show a constructor just as any other method, except we list no return type. Figure 3-20 shows a UML diagram for the Rectangle class with the constructor listed.

    Figure 3-20 UML diagram for the Rectangle class showing the constructor

    Rectangle

    - length : double - width : double + Rectangle(len : double, w : double) + setLength(len : double) : void + setWidth(w : double) : void + getLengthO : double + getWidthO : double + getAreaO : double

    The String Class Constructor The String class has a constructor that accepts a string literal as its argument, which is used to initialize the String object. The following statement creates a String object, passes the string literal "Joe Mahoney" to the constructor, and then stores the String object's address in the name variable. After the statement executes, the String object referenced by name will contain "Joe Mahoney".

    String name = new String("Joe Mahoney"); Because string operations are so common in programming, Java provides the shortcut nota-tion that we discussed earlier for creating and initializing String objects. For example, the

  • ''I

    144 Chapter 3 A First Look at Classes and Objects

    following statement creates a String object initialized with "Joe Mahoney" and assigns its address to the name variable.

    String name = "Joe Mahoney";

    ~ Checkpoint 3.12 How is a constructor named? 3.13 What is a constructor's return type? 3.14 Assume that the following is a constructor, which appears in a class.

    ClassAct(int number)

    item = number;

    a) What is the name of the class that this constructor appears in? b) Write a statement that creates an object from the class and passes the value 25

    as an argument to the constructor.

    A BankAccount Class The Rectangle class discussed in the previous section allows you to create objects that describe rectangles. Now we will look at a class that is modeled after a more tangible object: a bank account. Objects that are created from this class will simulate bank accounts, allow-ing us to perform operations such as making deposits, making withdrawals, calculating and adding interest, and getting the current balance. A UML diagram for the BankAccount class is shown in Figure 3-21.

    Figure 3-21 UML diagram for the BankAccount class

    BankAccount

    - balance: double - interestRate : double - interest: double

    + BankAccount(startBalance : double, intRate : double)

    + deposit(amount : double) : void + withdraw(amount : double) : void + addlnterestO : void + getBalanceO : double + getinterestO : double

    Here is a summary of the BankAccount class's fields:

    balance is a double that holds an account's current balance. interestRate is a double that holds the monthly interest rate for an account. The

    monthly interest rate is the annual interest rate divided by 12. For example, if the

    ,

  • ,

    3.5 A BankAccount Class 145

    annual interest rate is 3 percent, then the monthly interest rate is 0.25 percent. We would store this value as 0.0025 in the interestRate field .

    interest is a double that holds the amount of interest earned for an account.

    Here is a summary of the class's methods:

    The constructor has two parameter variables: startBalance and intRate. Both parameters are doubles. When the constructor executes, the account's starting bal-ance is passed into the startBalance parameter, and the account's monthly interest rate is passed into the intRate parameter. The constructor assigns startBalance to the balance field and intRate to the interestRate field. Additionally, the constructor assigns 0.0 to the interest field.

    The deposit method has a parameter, amount, that is a double . When the method is called, an amount that is to be deposited into the account is passed into this param-eter. The value of the parameter is then added to the value in the balance field.

    The withdraw method has a parameter, amount, that is a double . When the method is called, an amount that is to be withdrawn from the account is passed into this param-eter. The value of the parameter is then subtracted from the value in the bal ance field.

    The addInterest method multiplies the interestRate field by the balance field to determine the monthly interest for the account. The amount of interest is assigned to the interest field and added to the value in the balance field.

    The getBalance method returns the value in the balance field, which is the current account balance.

    The get Interest method returns the value in the interest field, which is the amount of interest earned the last time the addInterest method was called.

    Code listing 3-13 shows the code for the BankAccount class, which IS stored m the BankAccount.java file.

    Code Listing 3-13 (BankAccount.java)

    1 1** 2 * BankAccount class 3 * This class simulates a bank account. 4 *1 5 6 public class BankAccount 7 { 8 9

    10 11

    private double balance; private double interestRate ; private double interest ;

    12 1**

    II Account balance II Interest rate II Interest earned

    13 * The constructor initializes the balance 14 * and interestRate fields with the values 15 * passed to startBalance and intRate . The 16 * interest field is assigned 0.0. 17 *1 18 19 public BankAccount(double startBalance,

  • 146 Chapter 3 A First Look at Classes and Objects

    20 21 22 23 24 25 26 27 /**

    double intRate)

    balance = startBalance; interestRate = intRate ; interest = 0 . 0;

    28 * The deposit method adds the parameter 29 * amount to the balance field . 30 * / 31 32 public void deposit(double amount) 33 { 34 balance += amount; 35 36 37 /** 38 * The withdraw method subtracts the 39 40 41 42

    * parameter amount from the balance * field. */

    43 public void withdraw(double amount) 44 { 45 balance -= amount; 46 47 48 /** 49 * The addInterest method adds the 50 * interest for the month to the balance field. 51 * / 52 53 public void addInterest ( ) 54 { 55 interest balance * interestRate; 56 balance += interest; 57 58 59 /** 60 * The getBalance method returns the 61 * value in the balance field . 62 * / 63 64 public double getBalance() 65 { 66 return balance; 67 68 69 /** 70 * The get Interest method returns the 71 * value in the interest field . 72 * / 73

    ,

  • ,

    3.5 A BankAccount Class 147

    74 public double getlnterest() 75 { 76 return interest; 77 78

    The AccountTest.java program, shown in Code Listing 3-14, demonstrates the BankAccount class.

    Code Listing 3-14 (AccountTest. jav a )

    1 2 3 4 5 6 7 8 9

    10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

    import java . util . Scanner ; II Needed for the Scanner class

    1** * This program demonstrates the BankAccount class . *1

    public class AccountTest {

    public static void main(String[] args) {

    BankAccount account ; II To reference a BankAccount object double balance, II The account's starting balance

    interestRate , I I The monthly interest rate pay, II The user's pay cashNeeded ; II The amount of cash to

    II Create a Scanner object for keyboard input . Scanner keyboard = new Scanner(System . in) ;

    II Get the starting balance . System . out . pr int ("What is your account ' s "

    + "starting balance? " ) ; balance = keyboard . nextDouble() ;

    II Get the monthly interest rate .

    withdraw

    System .out . print( "What is your monthly interest rate? ") ; interestRate = keyboard . nextDouble() ;

    II Create a BankAccount object . account = new BankAccount(balance , interestRate) ;

    II Get the amount of pay for the month . System. out.print( "How much were you paid this month? ") ; pay = keyboard . nextDouble() ;

    I I Deposit the user's pay into the account . System . out.println ( "We will deposit your pay "

    + "into your account . ") ; account . deposit(pay) ; System . out . println ( "Your current balance is $"

    + account . getBalance()) ;

    II Withdraw some cash from the account .

  • 148 Chapter 3 A First Look at Classes and Objects

    44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

    System.ouLprint( "How much would you like" + "to withdraw? ");

    cashNeeded = keyboard.nextDouble(); account.withdraw(cashNeeded);

    II Add the monthly interest to the account . account.addInterest();

    II Display the interest earned and the balance. System.ouLprintln ( "This month you have earned $"

    + account.getInterest() + " in interest.");

    System.ouLprintln( "Now your balance is $" + account.getBalance());

    Program Output with Example Input Shown in Bold What is your account's starting balance? 500 [Enter] What is your monthly interest rate? 0.045 [Enter] How much were you paid this month? 1000 [Enter] We will deposit your pay into your account. Your current balance is $1500.0 How much would you like to withdraw? 900 [Enter] This month you have earned $27.0 in interest. Now your balance is $627.0

    Let's look at some of the details of this program. First, some variables are declared with the following statements, which appear in lines 11 through 15:

    BankAccount account; II To reference a BankAccount object double balance, II The account's starting balance

    interestRate , II The monthly interest rate pay, II The user's pay cashNeeded; II The amount of cash to withdraw

    The first variable declared is account . This is a variable that will be used later in the pro-gram to reference a BankAccount object. Note that the new key word is not used in this statement, so the variable does not yet reference an object. Then, the variables balance, interestRate, pay, and cashNeeded are declared. These will hold values that are input by the user.

    Next, the following code appears in lines 20 through 27:

    II Get the starting balance . System.out . print("What is your account ' s"

    + "starti ng balance? ") ; balance = keyboard . nextDouble();

    II Get the monthly interest rate . System.ouLprint ( "What is your monthly interest rate? "); interestRate = keyboard.nextDouble();

    ,

  • ,

    3.5 A BankAccount Class 149

    This code asks the user to enter his or her account's starting balance and the monthly interest rate. These values are stored in the balance and interestRate variables. Then, the following code appears in lines 29 through 30:

    II Create a BankAccount object. account = new BankAccount(balance, interestRate);

    The statement shown in line 30 uses the new key word to create a BankAccount object. The balance and interestRate variables are passed as arguments. Next, the following code appears in lines 32 through 41 :

    II Get the amount of pay for the month . System. out.print( "How much were you paid this month? "); pay = keyboard.nextDouble();

    II Deposit the user ' s pay into the account. System . out . println("We will deposit your pay"

    + "into your account . "); account.deposit(pay); System . out.println("Your current balance is $"

    + account . getBalance()); First, this code asks the user to enter his or her pay for the month. The input is stored in the pay variable. The account object's deposit method is called, and the pay variable is passed as an argument. Here is the code for the deposit method, which appears in the BankAccount class in lines 32 through 35:

    public void deposit(double amount) {

    balance += amount ;

    The value in pay is passed into the amount parameter variable. Then, the statement in this method uses a combined assignment operator to add amount to the value already in balance. This statement is the same as:

    balance = balance + amount;

    Back in the AccountTest program, the account object's getBalance method is then called in line 41 to get the current balance, which is displayed on the screen. Next, the following code appears in lines 43 through 47:

    II Withdraw some cash from the account. System. out.print( "How much would you like "

    + "to withdraw? ") ; cashNeeded = keyboard.nextDouble(); account.withdraw(cashNeeded) ;

    This code asks the user for the amount to withdraw from the account, and the input is stored in the cashNeeded variable. This variable is then passed as an argument to the account

  • 150 Chapter 3 A First Look at Classes and Objects

    object's withdraw method. Here is the code for the withdraw method, which appears in the BankAccount class, in lines 43 through 46:

    public void withdraw(double amount) {

    balance -= amount;

    The value in cashNeeded is passed into the amount parameter variable. Then, the statement in line 45 uses a combined assignment operator to subtract amount from the value already in balance. This statement is the same as:

    balance = balance - amount;

    Back in the AccountTest program, the following code appears in lines 49 through 57: II Add the monthly interest to the account. account.addInterest();

    II Display the interest earned and the balance. System.out.println("This month you have earned $"

    + account.getInterest() + " in interest.");

    System.out.println( "Now your balance is $" + account.getBalance());

    Line 50 calls the account object's addInterest method, which calculates an amount of interest, assigns that amount to the object's interest field, and adds that amount to the object's balance field. Then, the object's get Interest and getBalance methods are called to get the amount of interest and the current balance, which are displayed.

    Classes, Variables, and Scope CON C E P T: Instance fields are visible to all of the class's instance methods. Local

    variables, including parameter variables, are visible only to statements in the method where they are declared.

    Recall from Chapter 2 that a variable's scope is the part of a program where the variable can be accessed by its name. A variable's name is visible only to statements inside the variable's scope. The location of a variable's declaration determines the variable's scope. So far you have seen variables declared in the following locations:

    Inside a method. Variables declared inside a method are known as local variables. Inside a class, but not inside any method. Variables that are declared inside a class,

    but not inside any method are known as fields. Inside the parentheses of a method header. Variables that are declared inside the

    parentheses of a method header are known as parameter variables.

    The following list summarizes the scope for each of these types of variables.

    Local variables. A local variable's scope is the method in which it is declared, from the variable's declaration to the end of the method. Only statements in this area can access the variable.

    ,

  • ,

    3.7 Packages and import Statements 151

    Fields. For now we will define a field's scope as the entire class in which it is declared. A field can be accessed by the methods that are members of the same class as the field. (To be completely accurate, an instance field may be accessed by any instance method that is a member of the same class. In Chapter 7, we discuss non-instance class members.)

    Parameter variables. A parameter variable's scope is the method in which it is declared. Only statements inside the method can access the parameter variable.

    Shadowing In Chapter 2 you saw that you cannot have two local variables with the same name in the same scope. This applies to parameter variables as well. A parameter variable is, in essence, a local variable. So, you cannot give a parameter variable and a local variable in the same method the same name.

    However, you can have a local variable or a parameter variable with the same name as a field . When you do, the name of the local or parameter variable shadows the name of the field. This means that the field name is hidden by the name of the local or parameter variable.

    For example, assume that the Rectangle class's setLength method had been written in the following manner.

    public void setLength(double len) {

    int length ; II Local variable

    length = len;

    In this code a local variable is given the same name as the field. Therefore, the local vari-able's name shadows the field's name. When the statement length = len ; is executed, the value of len is assigned to the local variable length, not to the field. The unintentional shadowing of field names can cause elusive bugs, so you need to be careful not to give local variables the same names as fields.

    Packages and import Statements

    CONCEPT: The classes in the Java API are organized into packages. An import statement tells the compiler in which package a class is located.

    In Chapter 2 you were introduced to the Java API, which is a standard library of prewritten classes. Each class in the Java API is designed for a specific purpose, and you can use the classes in your own programs. You've already used a few classes from the API, such as the String class, the Scanner class, and the JOptionPane class.

    All of the classes in the Java API are organized into packages. A package is simply a group of related classes. Each package also has a name. For example, the Scanner class is in the java .util package.

  • 152 Chapter 3 A First Look at Classes and Objects

    Many of the classes in the Java API are not automatically available to your program. Quite often, you have to import an API class in order to use it. You use the import key word to import a class. For example, the following statement is required to import the Scanner class:

    import j ava.ut i l .Scanner; This statement tells the compiler that the Scanner class is located in the java. util package. Without this statement, the compiler will not be able to locate the Scanner class, and the program will not compile.

    Explicit and Wildcard import Statements There are two types of i mport statements: explicit and wildcard. An explicit import state-ment identifies the package location of a single class. For example, the following statement explicitly identifies the location of the Scanner class:

    import j ava.util.Scanner; The java. util package has several other classes in it as well as the Scanner class. For example, in Chapter 7 we will study the ArrayList class, and in Chapter 8 we will study the StringTokeni zer class. Both of these classes are part of the java. util package. If a pro- , gram needs to use the Scanner class, the ArrayList class, and the StringTokenizer class, it will have to import all three of these classes. One way to do this is to write explicit import statements for each class, as shown here:

    import java.util .Scanner; import java.util .ArrayList; import java.util .StringTokenizer;

    Another way to import all of these classes is to use a wildcard import statement. A wild-card import statement tells the compiler to import all of the classes in a package. Here is an example:

    import java.util .*; The . * that follows the package name tells the compiler to import all the classes that are part of the java.util package. Using a wildcard import statement does not affect the per-formance or the size of your program. It merely tells the compiler that you want to make every class in a particular package available to your program.

    The java. lang Package The Java API has one package, java .lang, that is automatically imported into every Java program. This package contains general classes, such as String and System, that are funda-mental to the Java programming language. You do not have to write an import statement for any class that is part of the java .lang package.

    Other API Packages There are numerous packages in the Java API. Table 3-2 lists a few of them.

  • 3.8 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 153

    Table 3-2 A few of the standard Java packages

    Package Description java . applet Provides the classes necessary to create an applet. java . awt Provides classes for the Abstract Windowing Toolkit. These classes are used in

    drawing images and creating graphical user interfaces. java . io Provides classes that perform various types of input and output. java . lang Provides general classes for the Java language. This package is automatically

    imported. java . net Provides classes for network communications. java . security Provides classes that implement security features. java . sql Provides classes for accessing databases using structured query language. java . text Provides various classes for formatting text. java. util Provides various utility classes. j avax . swing Provides classes for creating graphical user interfaces.

    00 See Appendix H on the Student CD for a more detailed look at packages. Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities

    CONCEPT: One of the first steps in creating an object-oriented application is determining the classes that are necessary, and their responsibilities within the application.

    So far you have learned the basics of writing a class, creating an object from the class, and using the object to perform operations. Although this knowledge is necessary to create an object-oriented application, it is not the first step. The first step is to analyze the problem that you are trying to solve and determine the classes that you will need. In this section we will discuss a simple technique for finding the classes in a problem and determining their responsibilities.

    Finding the Classes When developing an object-oriented application, one of your first tasks is to identify the classes that you will need to create. Typically, your goal is to identify the different types of real-world objects that are present in the problem, and then create classes for those types of objects within your application. Over the years, software professionals have developed numerous techniques for finding the classes in a given problem. One simple and popular technique involves the following steps.

  • 154 Chapter 3 A First Look at Classes and Objects

    1. Get a written description of the problem domain. 2. Identify all the nouns (including pronouns and noun phrases) in the description. Each

    of these is a potential class. 3. Refine the list to include only the classes that are relevant to the problem.

    Let's take a closer look at each of these steps.

    Writing a Description of the Problem Domain The problem domain is the set of real-world objects, parties, and major events related to the problem. If you adequately understand the nature of the problem you are try-ing to solve, you can write a description of the problem domain yourself. If you do not thoroughly understand the nature of the problem, you should have an expert write the description for you.

    For example, suppose we are programming an application that the manager of Joe's Automotive Shop will use to print service quotes for customers. Here is a description that an expert, perhaps Joe himself, might have written:

    Joe's Automotive Shop services foreign cars, and specializes in servicing cars made by Mercedes, Porsche, and BMW. When a customer brings a car to the shop, the manager , gets the customer's name, address, and telephone number. The manager then determines the make, model, and year of the car, and gives the customer a service quote. The service quote shows the estimated parts charges, estimated labor charges, sales tax, and total estimated charges.

    The problem domain description should include any of the following:

    Physical objects such vehicles, machines, or products Any role played by a person, such as manager, employee, customer, teacher, student,

    etc. The results of a business event, such as a customer order, or in this case a service

    quote Recordkeeping items, such as customer histories and payroll records

    Identify All of the Nouns The next step is to identify all of the nouns and noun phrases. (If the description contains pronouns, include them too.) Here's another look at the previous problem domain descrip-tion. This time the nouns and noun phrases appear in bold.

    Joe's Automotive Shop services foreign cars, and specializes in servicing cars made by Mercedes, Porsche, and BMW. When a customer brings a car to the shop, the manager gets the customer's name, address, and telephone number. The manager then determines the make, model, and year of the car, and gives the customer a service quote. The service quote shows the estimated parts charges, estimated labor charges, sales tax, and total estimated charges.

    Notice that some of the nouns are repeated. The following list shows all of the nouns with-out duplicating any of them.

  • \

    3.8 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 155

    address BMW car

    cars

    customer

    estimated labor charges estimated parts charges

    foreign cars Joe's Automotive Shop make manager Mercedes model name

    Refining the List of Nouns

    Porsche sales tax service quote shop telephone number total estimated charges year

    The nouns that appear in the problem description are merely candidates to become classes. It might not be necessary to make classes for them all. The next step is to refine the list to include only the classes that are necessary to solve the particular problem at hand. We will look at the common reasons that a noun can be eliminated from the list of potential classes.

    1. Some of the nouns really mean the same thing.

    In this example, the following sets of nouns refer to the same thing:

    cars and foreign cars These all refer to the general concept of a car .

    Joe's Automotive Shop and shop Both of these refer to the company "Joe's Automotive Shop."

    We can settle on a single class for each of these. In this example we will arbitrarily eliminate foreign cars from the list, and use the word cars. Likewise we will eliminate Joe's Automotive Shop from the list and use the word shop. The updated list of potential classes is: address BMW car

    cars

    customer

    estimated labor charges estimated parts charges Because cars and foreign cars mean the same thing in this foreign ears problem, we have eliminated foreign cars. Also, because Joe's Automotive Shop joe's Automotive Shop and shop mean the same thing, make we have eliminated joe's Automotive Shop. manager Mercedes model name

    Porsche sales tax

  • 156 Chapter 3 A First Look at Classes and Objects

    service quote shop telephone number total estimated charges year

    2. Some nouns might represent items that we do not need to be concerned with in order to solve the problem.

    A quick review of the problem description reminds us of what our application should do: print a service quote. In this example we can eliminate two unnecessary classes from the list:

    We can cross shop off the list because our application needs to be concerned only with individual service quotes. It doesn't need to work with or determine any company-wide information. If the problem description asked us to keep a total of all the service quotes, then it would make sense to have a class for the shop.

    We will not need a class for the manager because the problem statement does not direct us to process any information about the manager. If there were multiple shop managers, and the problem description had asked us to record which manager gener-ated each service quote, then it would make sense to have a class for the manager.

    The updated list of potential classes at this point is:

    address BMW car

    cars

    customer

    estimated labor charges estimated parts charges foreign cars Joe's Automotive Shop make manager Mercedes model name

    Porsche sales tax service quote

    telephone number total estimated charges year

    Our problem description does not direct us to process any information about the shop, or any information about the manager, so we have eliminated those from the list.

    \

  • \

    3.8 Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities 157

    3. Some of the nouns might represent objects, not classes. We can eliminate Mercedes, Porsche, and BMW as classes because, in this example, they all represent specific cars, and can be considered instances of a cars class. Also, we can eliminate the word car from the list. In the description it refers to a specific car brought to the shop by a customer. Therefore, it would also represent an instance of a cars class. At this point the updated list of potential classes is:

    address BMW

    cars

    customer

    estimated labor charges estimated parts charges foreign ears Joe's Atltomotive Shop manager make Mercedes model name

    Porsehe sales tax service quote shop telephone number total estimated charges year

    We have eliminated Mercedes, Porsche, BMW, and car because they are all instances of a cars class. That means that these nouns identify objects, not classes.

    TIP: Some object-oriented designers take note of whether a noun is plural or singu-lar. Sometimes a plural noun will indicate a class and a singular noun will indicate an object.

    4 . Some of the nouns might represent simple values that can be stored in a primitive variable and do not require a class.

    Remember, a class contains fields and methods. Fields are related items that are stored within an object of the class, and define the object's state. Methods are actions or behaviors that may be performed by an object of the class. If a noun represents a type of item that would not have any identifiable fields or methods, then it can probably be eliminated from the list. To help determine whether a noun represents an item that would have fields and methods, ask the following questions about it:

    Would you use a group of related values to repr