Using Objects Chapter 2 PDF
Document Details
Uploaded by LovedJasper
Tags
Summary
This chapter introduces the concepts of variables, classes, and objects in Java programming. It explains the difference between objects and object references, and how to utilize object methods and arguments. The chapter also details how to implement test programs and utilize the API documentation for various Java libraries.
Full Transcript
CHAPTER 2 USING OBJECTS CHAPTER GOALS To learn about variables To understand the concepts of classes and objects To be able to call methods © Lisa F....
CHAPTER 2 USING OBJECTS CHAPTER GOALS To learn about variables To understand the concepts of classes and objects To be able to call methods © Lisa F. Young/iStockphoto. To learn about arguments and return values To be able to browse the API documentation To implement test programs To understand the difference between objects and object references To write programs that display simple shapes CHAPTER CONTENTS 2.1 OBJECTS AND CLASSES 24 2.6 THE API DOCUMENTATION 41 SYN Importing a Class from a Package 43 2.2 VARIABLES 26 PT 3 Don’t Memorize—Use Online Help 43 SYN Variable Declaration 27 SYN Assignment 31 2.7 IMPLEMENTING A TEST CE 1 Using Undeclared or Uninitialized PROGRAM 44 Variables 32 ST 2 Testing Classes in an Interactive CE 2 Confusing Variable Declarations and Environment 45 Assignment Statements 32 WE1 How Many Days Have You Been Alive? 46 PT 1 Choose Descriptive Variable Names 32 WE2 Working with Pictures 46 ST 1 Variable Type Inference 33 2.8 OBJECT REFERENCES 46 2.3 CALLING METHODS 33 C&S Computer Monopoly 49 PT 2 Learn By Trying 37 2.9 GRAPHICAL APPLICATIONS 49 2.4 CONSTRUCTING OBJECTS 38 2.10 ELLIPSES, LINES, TEXT, SYN Object Construction 39 AND COLOR 54 CE 3 Trying to Invoke a Constructor Like a Method 40 2.5 ACCESSOR AND MUTATOR METHODS 40 23 bjeo_ch02p.indd 23 11/21/18 5:11 PM Most useful programs don’t just manipulate numbers and strings. Instead, they deal with data items that are more complex and that more closely represent entities in the real world. Examples of these data items include bank accounts, employee records, and graphical shapes. The Java language is ideally suited for designing and manipulating such data items, or objects. In Java, you implement classes that describe the behavior of these objects. In this chapter, you will learn how to manipulate objects that belong to classes that have already been implemented. This will prepare you for the next chapter, in which you will learn how to implement your own classes. 2.1 Objects and Classes © Lisa F. Young/iStockphoto. When you write a computer program, you put it together from certain “building blocks”. In Java, you build programs from objects. Each object has a particular behavior, and you can manipulate it to achieve certain effects. As an analogy, think of a home builder who constructs a house from certain parts: doors, windows, walls, pipes, a furnace, a water heater, and so on. Each of these elements has a particu- lar function, and they work together to fulfill a common purpose. Note that the home builder is not concerned with how to build a window or a water heater. These elements are readily avail- able, and the builder’s job is to integrate them © Luc Meaille/iStockphoto. into the house. Of course, computer programs are more Each part that a home builder uses, abstract than houses, and the objects that make such as a furnace or a water heater, up a computer program aren’t as tangible as a fulfills a particular function. Similarly, you build programs from objects, each window or a water heater. But the analogy of which has a particular behavior. holds well: A programmer produces a working program from elements with the desired functionality—the objects. In this chapter, you will learn the basics about using objects written by other programmers. 2.1.1 Using Objects Objects are entities An object is an entity that you can manipulate by calling one or more of its methods. in your program that A method consists of a sequence of instructions that can access the internal data of an you manipulate by object. When you call the method, you do not know exactly what those instructions calling methods. are, or even how the object is organized internally. However, the behavior of the method is well defined, and that is what matters to us when we use it. 24 bjeo_ch02p.indd 24 11/21/18 5:12 PM 2.1 Objects and Classes 25 The class that the PrintStream System.out object belongs to 10101110 data = 11110110 01101011 00110101 The object’s internal data println Methods you can print call on System.out Figure 1 Representation of the System.out Object A method is a For example, you saw in Chapter 1 that System.out refers to an object. You manipu- sequence of late it by calling the println method. When the println method is called, some activi- instructions that ties occur inside the object, and the ultimate effect is that text appears in the console accesses the data of an object. window. You don’t know how that happens, and that’s OK. What matters is that the method carries out the work that you requested. Figure 1 shows a representation of the System.out object. The internal data is sym- bolized by a sequence of zeroes and ones. Think of each method (symbolized by the gears) as a piece of machinery that carries out its assigned task. In general, think of an object as an entity that can do work for you when you call its methods. How the work is done is not important to the programmer using the object. In the remainder of this chapter, you will see other objects and the methods that they can carry out. You can think of a water heater as an object that can carry out the “get hot water” method. When you call that method to enjoy a hot shower, you don’t care whether the water heater uses gas or solar power. © Steven Frame/iStockphoto. 2.1.2 Classes In Chapter 1, you encountered two objects: System.out "Hello, World!" Each of these objects belongs to a different class. The System.out object belongs to the PrintStream class. The "Hello, World!" object belongs to the String class. Of course, there are many more String objects, such as "Goodbye" or "Mississippi". They all have something in common—you can invoke the same methods on all strings. You will see some of these methods in Section 2.3. A class describes As you will see in Chapter 11, you can construct objects of the PrintStream class a set of objects with other than System.out. Those objects write data to files or other destinations instead of the same behavior. the console. Still, all PrintStream objects share common behavior. You can invoke the bjeo_ch02p.indd 25 11/21/18 5:12 PM 26 Chapter 2 Using Objects println and print methods on any PrintStream object, and the printed values are sent to their destination. Of course, the objects of the Print- Stream class have a completely different behavior than the objects of the String class. You could not call println on a String object. A string wouldn’t know how to send itself to a console window or file. As you can see, different classes have different responsibilities. A string knows about the letters that it contains, but it © Arcaid Images/Alamy Inc. does not know how to display them to a All objects of a Window class share the same human or to save them to a file. behavior. 2.2 Variables Before we continue with the main topic of this chapter—the behavior of objects—we need to go over some basic programming terminology. In the following sections, you will learn about the concepts of variables, types, and assignment. 2.2.1 Variable Declarations When your program manipulates objects, you will want to store the objects and the values that their methods return, so that you can use them later. In a Java program, you use variables to store values. The following statement declares a variable named width: int width = 20; A variable is a A variable is a storage location in a computer program. Each variable has a name and storage location holds a value. with a name. A variable is similar to a parking space in a parking garage. The parking space has an identifier (such as “J 053”), and it can hold a vehicle. A variable has a name (such as width), and it can hold a value (such as 20). Like a variable in a computer program, a parking space has an identifier and contents. Javier Larrea/Age Fotostock. bjeo_ch02p.indd 26 11/21/18 5:12 PM 2.2 Variables 27 Syntax 2.1 Variable Declaration Syntax typeName variableName = value; or typeName variableName; See Table 2 for rules and examples of valid names. The type specifies A variable declaration ends what can be done String greeting = "Hello, Dave!"; with a semicolon. with values stored in this variable. Supplying an initial value is optional, Use a descriptive but it is usually a good idea. variable name. See Programming Tip 2.1. When declaring a When declaring a variable, you usually want to initialize it. That is, you specify the variable, you value that should be stored in the variable. Consider again this variable declaration: usually specify an initial value. int width = 20; The variable width is initialized with the value 20. When declaring a Like a parking space that is restricted to a certain type of vehicle (such as a compact variable, you also car, motorcycle, or electric vehicle), a variable in Java stores data of a specific type. specify the type of Java supports quite a few data types: numbers, text strings, files, dates, and many oth- its values. ers. You must specify the type whenever you declare a variable (see Syntax 2.1). The width variable is an integer, a whole number without a fractional part. In Java, this type is called int. Note that the type comes before the variable name: int width = 20; After you have declared and initialized a variable, you can use it. For example, int width = 20; System.out.println(width); int area = width * width; Table 1 shows several examples of variable declarations. Each parking space is suitable for a particular type of vehicle, just as each variable holds a value of a particular type. © Ingenui/iStockphoto. bjeo_ch02p.indd 27 11/21/18 5:12 PM 28 Chapter 2 Using Objects Table 1 Variable Declarations in Java Variable Name Comment int width = 20; Declares an integer variable and initializes it with 20. int perimeter = 4 * width; The initial value need not be a fixed value. (Of course, width must have been previously declared.) String greeting = "Hi!"; This variable has the type String and is initialized with the string “Hi”. height = 30; Error: The type is missing. This statement is not a declaration but an assignment of a new value to an existing variable—see Section 2.2.5. int width = "20"; Error: You cannot initialize a number with the string “20”. (Note the quotation marks.) int width; Declares an integer variable without initializing it. This can be a cause for errors—see Common Error 2.1. int width, height; Declares two integer variables in a single statement. In this book, we will declare each variable in a separate statement. 2.2.2 Types Use the int type In Java, there are several different types of numbers. You use the int type to denote a for numbers that whole number without a fractional part. For example, suppose you count the num- cannot have a ber of cars in a parking lot. The counter must be an integer number—you cannot have fractional part. a fraction of a car. When a fractional part is required (such as in the number 22.5), we use floating- point numbers. The most commonly used type for floating-point numbers in Java is called double. Here is the declaration of a floating-point variable: double milesPerGallon = 22.5; Use the double You can combine numbers with the + and - operators, as in width + 10 or width - 1. To type for floating- multiply two numbers, use the * operator. For example, 2 × width is written as point numbers. 2 * width. Use the / operator for division, such as width / 2. As in mathematics, the * and / operator bind more strongly than the + and - opera- Numbers can tors. That is, width + height * 2 means the sum of width and the product height * 2. If be combined by you want to multiply the sum by 2, use parentheses: (width + height) * 2. arithmetic operators such as +, -, and *. Not all types are number types. For example, the value "Hello" has the type String. You need to specify that type when you define a variable that holds a string: String greeting = "Hello"; A type specifies the operations that can be carried out with its values. Types are important because they indicate what you can do with a variable. For example, consider the variable width. It’s type is int. Therefore, you can multiply the value that it holds with another number. But the type of greeting is String. You can’t multiply a string with another number. (You will see in Section 2.3.1 what you can do with strings.) bjeo_ch02p.indd 28 11/21/18 5:12 PM 2.2 Variables 29 2.2.3 Names When you declare a variable, you should pick a name that explains its purpose. For example, it is better to use a descriptive name, such as milesPerGallon, than a terse name, such as mpg. In Java, there are a few simple rules for the names of variables, methods, and classes: 1. Names must start with a letter or the underscore (_) character, and the remain- ing characters must be letters, numbers, or underscores. (Technically, the $ symbol is allowed as well, but you should not use it—it is intended for names that are automatically generated by tools.) 2. You cannot use other symbols such as ? or %. Spaces are not permitted inside names either. You can use uppercase letters to denote word boundaries, as in milesPerGallon. This naming convention is called camel case because the uppercase letters in the middle of the name look like the humps of a camel.) © GlobalP/iStockphoto. 3. Names are case sensitive, that is, milesPerGallon and milespergallon are different names. 4. You cannot use reserved words such as double or class as names; these words are reserved exclusively for their special Java meanings. (See Appendix C for a listing of all reserved words in Java.) By convention, It is a convention among Java programmers that names of variables and methods start variable names with a lowercase letter (such as milesPerGallon). Class names should start with an should start with a uppercase letter (such as HelloPrinter). That way, it is easy to tell them apart. lowercase letter. Table 2 shows examples of legal and illegal variable names in Java. Table 2 Variable Names in Java Variable Name Comment distance_1 Names consist of letters, numbers, and the underscore character. x In mathematics, you use short variable names such as x or y. This is legal in Java, but not very common, because it can make programs harder to understand (see Programming Tip 2.1). ! CanVolume Caution: Names are case sensitive. This variable name is different from canVolume, and it violates the convention that variable names should start with a lowercase letter. 6pack Error: Names cannot start with a number. can volume Error: Names cannot contain spaces. double Error: You cannot use a reserved word as a name. miles/gal Error: You cannot use symbols such as / in names. bjeo_ch02p.indd 29 11/21/18 5:12 PM 30 Chapter 2 Using Objects 2.2.4 Comments As your programs get more complex, you should add comments, explanations for human readers of your code. For example, here is a comment that explains the value used to initialize a variable: double milesPerGallon = 35.5; // The average fuel efficiency of new U.S. cars in 2013 This comment explains the significance of the value 35.5 to a human reader. The com- piler does not process comments at all. It ignores everything from a // delimiter to the end of the line. Use comments to It is a good practice to provide comments. This helps programmers who read your add explanations code understand your intent. In addition, you will find comments helpful when you for humans who review your own programs. read your code. The compiler ignores You use the // delimiter for short comments. If you have a longer comment, comments. enclose it between delimiters. The compiler ignores these delimiters and everything in between. For example, double fuelEfficiency = 235.214583 / milesPerGallon; 2.2.5 Assignment Use the assignment You can change the value of a variable with the assignment operator (=). For example, operator (=) to consider the variable declaration change the value of a variable. int width = 10; ❶ If you want to change the value of the variable, simply assign the new value: width = 20; ❷ The assignment replaces the original value of the variable (see Figure 2). 1 width = 10 2 Figure 2 width = 20 Assigning a New Value to a Variable It is an error to use a variable that has never had a value assigned to it. For example, the following assignment statement has an error: int height; int width = height; // ERROR—uninitialized variable height The compiler will complain about an “uninitialized variable” when you use a vari- able that has never been assigned a value. (See Figure 3.) Figure 3 No value has been assigned. height = An Uninitialized Variable bjeo_ch02p.indd 30 11/21/18 5:12 PM 2.2 Variables 31 Syntax 2.2 Assignment Syntax variableName = value; double width = 20; This is a variable declaration... This is an assignment statement. width = 30; The value of this variable is changed.. The new value of the variable.. width = width + 10; The same name can occur on both sides. See Figure 4. All variables must be The remedy is to assign a value to the variable before you use it: initialized before you int height = 20; access them. int width = height; // OK The right-hand side of the = symbol can be a mathematical expression. For example, width = height + 10; This means “compute the value of height + 10 and store that value in the variable width”. The assignment In the Java programming language, the = operator denotes an action, namely to operator = does not replace the value of a variable. This usage differs from the mathematical usage of the = denote mathematical symbol as a statement about equality. For example, in Java, the following statement is equality. entirely legal: width = width + 10; This means “compute the value of width + 10 ❶ and store that value in the variable width ❷” (see Figure 4). In Java, it is not a problem that the variable width is used on both sides of the = sym- bol. Of course, in mathematics, the equation width = width + 10 has no solution. 1 Compute the value of the right-hand side width = 30 width + 10 40 2 Store the value in the variable Figure 4 width = 40 Executing the Statement width = width + 10 bjeo_ch02p.indd 31 11/21/18 5:12 PM 32 Chapter 2 Using Objects EXAMPLE CODE See sec02 of your eText or companion code for a program that demonstrates variables and assignments. Common Error 2.1 Using Undeclared or Uninitialized Variables © John Bell/iStockphoto. You must declare a variable before you use it for the first time. For example, the following sequence of statements would not be legal: int perimeter = 4 * width; // ERROR: width not yet declared int width = 20; In your program, the statements are compiled in order. When the compiler reaches the first statement, it does not know that width will be declared in the next line, and it reports an error. The remedy is to reorder the declarations so that each variable is declared before it is used. A related error is to leave a variable uninitialized: int width; int perimeter = 4 * width; // ERROR: width not yet initialized The Java compiler will complain that you are using a variable that has not yet been given a value. The remedy is to assign a value to the variable before it is used. Common Error 2.2 Confusing Variable Declarations and Assignment Statements © John Bell/iStockphoto. Suppose your program declares a variable as follows: int width = 20; If you want to change the value of the variable, you use an assignment statement: width = 30; It is a common error to accidentally use another variable declaration: int width = 30; // ERROR—starts with int and is therefore a declaration But there is already a variable named width. The compiler will complain that you are trying to declare another variable with the same name. Programming Tip 2.1 Choose Descriptive Variable Names In algebra, variable names are usually just one letter long, such as p or A, maybe with a sub- © Eric Isselé/iStockphoto. script such as p1. You might be tempted to save yourself a lot of typing by using short variable names in your Java programs: int a = w * h; Compare that statement with the following one: int area = width * height; The advantage is obvious. Reading width is much easier than reading w and then figuring out that it must mean “width”. In practical programming, descriptive variable names are particularly important when pro- grams are written by more than one person. It may be obvious to you that w stands for width, but is it obvious to the person who needs to update your code years later? For that matter, will you yourself remember what w means when you look at the code a month from now? bjeo_ch02p.indd 32 11/21/18 5:12 PM 2.3 Calling Methods 33 Special Topic 2.1 Variable Type Inference As of Java 10, you need not specify the type of a variable that you initialize. For example, instead of double milesPerGallon = 22.5; © Eric Isselé/iStockphoto. String greeting = "Hello"; you can write: var milesPerGallon = 22.5; var greeting = "Hello"; The Java compiler infers the type of the variable from the type of the initial value. This is a convenient shortcut for longer type names. However, the explicit types provide useful infor- mation, and we will not use the var syntax in this book. 2.3 Calling Methods A program performs useful work by calling methods on its objects. In this section, we examine how to supply values in a method, and how to obtain the result of the method. 2.3.1 The Public Interface of a Class You use an object by calling its methods. All objects of a given class share a common set of methods. For example, the PrintStream class provides methods for its objects (such as println and print). Similarly, the String class provides methods that you can apply to String objects. One of them is the length method. The length method counts the number of characters in a string. You can apply that method to any object of type String. For example, the sequence of statements: String greeting = "Hello, World!"; int numberOfCharacters = greeting.length(); sets numberOfCharacters to the length of the String object "Hello, World!". After the instructions in the length method are executed, numberOfCharacters is set to 13. (The quotation marks are not part of the string, and the length method does not count them.) When calling the length method, you do not supply any values inside the parenthe- ses. Also note that the length method does not produce any visible output. It returns a value that is subsequently used in the program. Let’s look at another method of the String class. When you apply the toUpperCase method to a String object, the method creates another String object that contains the characters of the original string, with lowercase letters converted to uppercase. For example, the sequence of statements String river = "Mississippi"; String bigRiver = river.toUpperCase(); sets bigRiver to the String object "MISSISSIPPI". bjeo_ch02p.indd 33 11/21/18 5:12 PM 34 Chapter 2 Using Objects The public interface The String class declares many other of a class specifies methods besides the length and toUpper- what you can do Case methods—you will learn about with its objects. The hidden imple- many of them in Chapter 4. Collectively, mentation describes the methods form the public interface of how these actions the class, telling you what you can do are carried out. with the objects of the class. A class also declares a private implementation, describing the data inside its objects and the instructions for its methods. Those details are hidden from the programmers who use objects and call methods. © Damir Cudic/iStockphoto. Figure 5 shows two objects of the The controls of a car form its public interface. String class. Each object stores its own The private implementation is under the hood. data (drawn as boxes that contain char- acters). Both objects support the same set of methods—the public interface that is specified by the String class. String String data = H e l l o... data = M i s s i... length length toUpperCase toUpperCase Figure 5 A Representation of Two String Objects 2.3.2 Method Arguments An argument is a Most methods require values that give details about the work that the method needs value that is supplied to do. For example, when you call the println method, you must supply the string in a method call. that should be printed. Computer scientists use the technical term argument for method inputs. PrintStream 10101110 11110110 01101011 00110101 "Hello, World" println print Figure 6 Passing an Argument to the println Method bjeo_ch02p.indd 34 11/21/18 5:12 PM 2.3 Calling Methods 35 We say that the string greeting is an argument of the method call System.out.println(greeting); Figure 6 illustrates passing the argument to the method. Some methods require multiple arguments; others don’t require any arguments at all. An example of the latter is the length method of the String class (see Figure 7). All the information that the length method requires to do its job—namely, the character sequence of the string—is stored in the object that carries out the method. String H e l l o... (no argument) length 13 Figure 7 Invoking the length Method toUpperCase on a String Object 2.3.3 Return Values The return value of Some methods, such as the println method, carry out an action for you. Other meth- a method is a result ods compute and return a value. For example, the length method returns a value, that the method has namely the number of characters in the string. You can store the return value in a computed. variable: int numberOfCharacters = greeting.length(); You can also use the return value of one method as an argument of another method: System.out.println(greeting.length()); The method call greeting.length() returns a value—the integer 13. The return value becomes an argument of the println method. Figure 8 shows the process. Not all methods return values. One example is the println method. The println method interacts with the operating system, causing characters to appear in a win- dow. But it does not return a value to the code that calls it. String PrintStream 10101110 11110110 H e l l o... 01101011 00110101 (no argument) length 13 println toUpperCase print Figure 8 Passing the Result of a Method Call to Another Method bjeo_ch02p.indd 35 11/21/18 5:12 PM 36 Chapter 2 Using Objects At this tailor shop, the customer’s measurements and the fabric are the arguments of the sew method. The return value is the finished garment. © Loentura/iStockphoto. Let us analyze a more complex method call. Here, we will call the replace method of the String class. The replace method carries out a search-and-replace operation, similar to that of a word processor. For example, the call river.replace("issipp", "our") constructs a new string that is obtained by replacing all occurrences of "issipp" in "Mississippi" with "our". (In this situation, there was only one replacement.) The method returns the String object "Missouri". You can save that string in a variable: river = river.replace("issipp", "our"); Or you can pass it to another method: System.out.println(river.replace("issipp", "our")); As Figure 9 shows, this method call Is invoked on a String object: "Mississippi" Has two arguments: the strings "issipp" and "our" Returns a value: the string "Missouri" String M i s s i... length toUpperCase "issipp" replace "Missouri" "our" Figure 9 Calling the replace Method 2.3.4 Method Declarations When a method is declared in a class, the declaration specifies the types of the argu- ments and the return value. For example, the String class declares the length method as public int length() bjeo_ch02p.indd 36 11/21/18 5:12 PM 2.3 Calling Methods 37 Table 3 Method Arguments and Return Values Example Comments System.out.println(greeting) greeting is an argument of the println method. greeting.replace("e","3") The replace method has two arguments, in this case "e" and "3". greeting.length() The length method has no arguments. int n = greeting.length(); The length method returns an integer value. System.out.println(n); The println method returns no value. In the API documentation, its return type is void. System.out.println(greeting.length()); The return value of one method can become the argument of another. That is, there are no arguments, and the return value has the type int. (For now, all the methods that we consider will be “public” methods—see Chapter 9 for more restricted methods.) The replace method is declared as public String replace(String target, String replacement) To call the replace method, you supply two arguments, target and replacement, which both have type String. The returned value is another string. When a method returns no value, the return type is declared with the reserved word void. For example, the PrintStream class declares the println method as public void println(String output) Occasionally, a class declares two methods with the same name and different argu- ment types. For example, the PrintStream class declares a second method, also called println, as public void println(int output) That method is used to print an integer value. We say that the println name is over- loaded because it refers to more than one method. EXAMPLE CODE See sec03 of your eText or companion code for a program that demonstrates method calls. Programming Tip 2.2 Learn By Trying When you learn about a new method, write a small program to try it out. For example, you can © Eric Isselé/iStockphoto. go right now to your Java development environment and run this program: public class ReplaceDemo { public static void main(String[] args) { String river = "Mississippi"; System.out.println(river.replace("issipp", "our")); } } bjeo_ch02p.indd 37 11/21/18 5:12 PM 38 Chapter 2 Using Objects Then you can see with your own eyes what the replace method does. Also, you can run experi- ments. Does replace change every match, or only the first one? Try it out: System.out.println(river.replace("i", "x")); Set up your work environment to make this kind of experimentation easy and natural. Keep a file with the blank outline of a Java program around, so you can copy and paste it when needed. Some development environments let you type commands into a window and show you the result right away, without having to make a main method, and without calling System.out.println (see Figure 10). Figure 10 The BlueJ Code Pad and JShell 2.4 Constructing Objects Generally, when you want to use objects in your pro- gram, you need to specify their initial properties by constructing them. To learn about object construction, we need to go beyond String objects and the System.out object. Let us turn to another class in the Java library: the Rectangle class. Objects of type Rectangle describe rectangular shapes. These objects are useful for a variety of pur- poses. You can assemble rectangles into bar charts, and you can program simple games by moving rectangles inside a window. © sinankocasian/iStockphoto. Note that a Rectangle object isn’t a rectangular Objects of the Rectangle class shape—it’s an object that contains a set of numbers. describe rectangular shapes. The numbers describe the rectangle (see Figure 11). Each rectangle is described by the x- and y-coordinates of its top-left corner, its width, and its height. bjeo_ch02p.indd 38 11/29/18 3:58 PM 2.4 Constructing Objects 39 Rectangle Rectangle Rectangle x = 5 x = 35 x = 45 y = 10 y = 30 y = 0 width = 20 width = 20 width = 30 height = 30 height = 20 30 height = 20 30 Figure 11 Rectangle Objects It is very important that you understand this distinction. In the computer, a Rect- angle object is a block of memory that holds four numbers, for example x = 5, y = 10, width = 20, height = 30. In the imagination of the programmer who uses a Rectangle object, the object describes a geometric figure. Use the new To make a new rectangle, you need to specify the x, y, width, and height values. operator, followed Then invoke the new operator, specifying the name of the class and the argument(s) by a class name required for constructing a new object. For example, you can make a new rectangle and arguments, to construct with its top-left corner at (5, 10), width 20, and height 30 as follows: new objects. new Rectangle(5, 10, 20, 30) Here is what happens in detail: 1. The new operator makes a Rectangle object. 2. It uses the arguments (in this case, 5, 10, 20, and 30) to initialize the object’s data. 3. It returns the object. The process of creating a new object is called construction. The four values 5, 10, 20, and 30 are called the construction arguments. The new expression yields an object, and you need to store the object if you want to use it later. Usually you assign the output of the new operator to a variable. For example, Rectangle box = new Rectangle(5, 10, 20, 30); Syntax 2.3 Object Construction Syntax new ClassName(arguments) The new expression yields an object. Construction arguments Rectangle box = new Rectangle(5, 10, 20, 30); Usually, you save the constructed object System.out.println(new Rectangle()); in a variable. Supply the parentheses even when You can also there are no arguments. pass a constructed object to a method. bjeo_ch02p.indd 39 11/30/18 1:45 PM 40 Chapter 2 Using Objects Some classes let you construct objects in multiple ways. For example, you can also obtain a Rectangle object by supplying no construction arguments at all (but you must still supply the parentheses): new Rectangle() This expression constructs a (rather useless) rectangle with its top-left corner at the origin (0, 0), width 0, and height 0. EXAMPLE CODE See sec04 of your eText or companion code for a program that demonstrates constructors. Common Error 2.3 Trying to Invoke a Constructor Like a Method © John Bell/iStockphoto. Constructors are not methods. You can only use a constructor with the new operator, not to reinitialize an existing object: box.Rectangle(20, 35, 20, 30); // Error—can’t reinitialize object The remedy is simple: Make a new object and overwrite the current one stored by box. box = new Rectangle(20, 35, 20, 30); // OK 2.5 Accessor and Mutator Methods An accessor method In this section we introduce a useful terminology for the methods of a class. A method does not change the that accesses an object and returns some information about it, without changing the internal data of the object, is called an accessor method. In contrast, a method whose purpose is to mod- object on which it is invoked. A mutator ify the internal data of an object is called a mutator method. method changes For example, the length method of the String class is an accessor method. It returns the data. information about a string, namely its length. But it doesn’t modify the string at all when counting the characters. The Rectangle class has a number of accessor methods. The getX, getY, getWidth, and getHeight methods return the x- and y-coordinates of the top-left corner, the width, and the height values. For example, double width = box.getWidth(); Now let us consider a mutator method. Programs that manipulate rectangles fre- quently need to move them around, for example, to display animations. The Rectangle class has a method for that purpose, called translate. (Mathematicians use the term “translation” for a rigid motion of the plane.) This method moves a rectangle by a certain distance in the x- and y-directions. The method call, box.translate(15, 25); moves the rectangle by 15 units in the x-direction and 25 units in the y-direction (see Figure 12 Figure 12). Moving a rectangle doesn’t change its width or height, but it changes the Using the translate top-left corner. Afterward, the rectangle that had its top-left corner at (5, 10) now has Method to Move a it at (20, 35). Rectangle This method is a mutator because it modifies the object on which the method is invoked. EXAMPLE CODE See sec05 of your eText or companion code for a program that demonstrates accessors and mutators. bjeo_ch02p.indd 40 11/21/18 5:12 PM 2.6 The API Documentation 41 2.6 The API Documentation The API (Application The classes and methods of the Java library are listed in the API documentation. The Programming Inter- API is the “application programming interface”. A programmer who uses the Java face) documentation classes to put together a computer program (or application) is an application pro- lists the classes and methods of grammer. That’s you. In contrast, the programmers who designed and implemented the Java library. the library classes such as PrintStream and Rectangle are system programmers. You can find the API documentation on the Web. Point your web browser to http://docs.oracle.com/javase/10/docs/api/index.html. An abbreviated version of the API documentation is provided in Appendix D that may be easier to use at first, but you should eventually move on to the real thing. 2.6.1 Browsing the API Documentation The API documentation documents all classes in the Java library—there are thou- sands of them (see Figure 13, top). Most of the classes are rather specialized, and only a few are of interest to the beginning programmer. Locate the Rectangle link in the left pane, preferably by using the search function of your browser. Click on the link, and the right pane shows all the features of the Rect- angle class (see Figure 13, bottom). API documentation of the Rectangle class Scroll down Figure 13 The API Documentation of the Standard Java Library bjeo_ch02p.indd 41 11/21/18 5:12 PM 42 Chapter 2 Using Objects API documentation of the translate method 1 2 Figure 14 The Method Summary for the Rectangle Class The API documentation for each class starts out with a section that describes the purpose of the class. Then come summary tables for the constructors and methods (see Figure 14, top). Click on a method’s link to get a detailed description (see Figure 14, bottom). The detailed description of a method shows The action that the method carries out. ❶ The types and names of the parameter variables that receive the arguments when the method is called. ❷ The value that it returns (or the reserved word void if the method doesn’t return any value). As you can see, the Rectangle class has quite a few methods. While occasionally intim- idating for the beginning programmer, this is a strength of the standard library. If you ever need to do a computation involving rectangles, chances are that there is a method that does all the work for you. For example, suppose you want to change the width or height of a rectangle. If you browse through the API documentation, you will find a setSize method with the description “Sets the size of this Rectangle to the specified width and height.” The method has two arguments, described as width - the new width for this Rectangle height - the new height for this Rectangle bjeo_ch02p.indd 42 11/29/18 3:58 PM 2.6 The API Documentation 43 We can use this information to change the box object so that it is a square of side length 40. The name of the method is setSize, and we supply two arguments: the new width and height: box.setSize(40, 40); 2.6.2 Packages The API documentation contains another important piece of information about each class. The classes in the standard library are organized into packages. A package is a collection of classes with a related purpose. The Rectangle class belongs to the pack- age java.awt (where awt is an abbreviation for “Abstract Windowing Toolkit”), which contains many classes for drawing windows and graphical shapes. You can see the package name java.awt in Figure 13, just above the class name. Java classes are To use the Rectangle class from the java.awt package, you must import the package. grouped into Simply place the following line at the top of your program: packages. Use the import statement import java.awt.Rectangle; to use classes that Why don’t you have to import the System and String classes? Because the System and are declared in other packages. String classes are in the java.lang package, and all classes from this package are auto- matically imported, so you never need to import them yourself. Syntax 2.4 Importing a Class from a Package Syntax import packageName.ClassName; Package name Class name Import statements import java.awt.Rectangle; must be at the top of the source file. You can look up the package name in the API documentation. Programming Tip 2.3 Don’t Memorize—Use Online Help The Java library has thousands of classes and methods. It is neither necessary nor useful trying © Eric Isselé/iStockphoto. to memorize them. Instead, you should become familiar with using the API documentation. Because you will need to use the API documentation all the time, it is best to download and install it onto your computer, particularly if your computer is not always connected to the Internet. You can download the documentation from http://www.oracle.com/technetwork/java/ javase/downloads/index.html. bjeo_ch02p.indd 43 11/21/18 5:12 PM 44 Chapter 2 Using Objects Testing Track 2.7 Implementing a Test Program A test program In this section, we discuss the steps that are necessary to implement a test program. verifies that methods The purpose of a test program is to verify that one or more methods have been imple- behave as expected. mented correctly. A test program calls methods and checks that they return the expected results. Writing test programs is a very important skill. In this section, we will develop a simple program that tests a method in the Rectangle class using these steps: 1. Provide a tester class. 2. Supply a main method. 3. Inside the main method, construct one or more objects. 4. Apply methods to the objects. 5. Display the results of the method calls. 6. Display the values that you expect to get. Our sample test program tests the behavior of the translate method. Here are the key steps (which have been placed inside the main method of the MoveTester class). Rectangle box = new Rectangle(5, 10, 20, 30); // Move the rectangle box.translate(15, 25); // Print information about the moved rectangle System.out.print("x: "); System.out.println(box.getX()); System.out.println("Expected: 20"); We print the value that is returned by the getX method, and then we print a message that describes the value we expect to see. Determining the This is a very important step. You want to spend some time thinking about the expected result expected result before you run a test program. This thought process will help you in advance is an understand how your program should behave, and it can help you track down errors important part of testing. at an early stage. Finding and fixing errors early is a very effective strategy that can save you a great deal of time. In our case, the rectangle has been constructed with the top-left corner at (5, 10). The x-direction is moved by 15, so we expect an x-value of 5 + 15 = 20 after the move. Here is the program that tests the moving of a rectangle. sec07/MoveTester.java 1 import java.awt.Rectangle; 2 3 public class MoveTester 4 { 5 public static void main(String[] args) 6 { 7 Rectangle box = new Rectangle(5, 10, 20, 30); 8 9 // Move the rectangle 10 box.translate(15, 25); 11 bjeo_ch02p.indd 44 11/29/18 3:58 PM Testing Track 2.7 Implementing a Test Program 45 12 // Print information about the moved rectangle 13 System.out.print("x: "); 14 System.out.println(box.getX()); 15 System.out.println("Expected: 20"); 16 17 System.out.print("y: "); 18 System.out.println(box.getY()); 19 System.out.println("Expected: 35"); 20 } 21 } Program Run x: 20 Expected: 20 y: 35 Expected: 35 Special Topic 2.2 Testing Classes in an Interactive Environment Some development environments are specifically designed to help students explore objects without having to provide tester classes. These environments can be very helpful for gaining insight into the behavior of objects, and for promoting object-oriented thinking. The BlueJ © Eric Isselé/iStockphoto. environment (shown in the figure) displays objects as blobs on a workbench. You can construct new objects, put them on the workbench, invoke methods, and see the return values, all without writing a line of code. You can download BlueJ at no charge from http://www.bluej.org. Another excellent environment for interactively exploring objects is Dr. Java at http://drjava.sourceforge.net. Testing a Method Call in BlueJ bjeo_ch02p.indd 45 11/21/18 5:12 PM 46 Chapter 2 Using Objects WORKED E XAMP LE 2.1 © Constance Bannister Corp/Hulton Archive/ How Many Days Have You Been Alive? Getty Images, Inc. Explore the API of a class Day that represents a calendar day. Using that class, learn to write a program that computes how many days © Tom Horyn/iStockphoto. have elapsed since the day you were born. See your eText or visit wiley.com/go/bjeo7. WORKED E XAMP LE 2.2 Working with Pictures Learn how to use the API of a Picture class to edit photos. See your eText or visit wiley.com/go/bjeo7. © Tom Horyn/iStockphoto. Cay Horstmann. 2.8 Object References In Java, an object variable (that is, a variable whose type is a class) does not actually hold an object. It merely holds the memory location of an object. The object itself is stored elsewhere—see Figure 15. box = Rectangle x = 5 y = 10 Figure 15 width = 20 An Object Variable height = 30 Containing an Object Reference There is a reason for this behavior. Objects can be very large. It is more efficient to store only the memory location instead of the entire object. An object reference We use the technical term object reference to denote the memory location of an describes the object. When a variable contains the memory location of an object, we say that it location of an object. refers to an object. For example, after the statement Rectangle box = new Rectangle(5, 10, 20, 30); the variable box refers to the Rectangle object that the new operator constructed. Tech- nically speaking, the new operator returned a reference to the new object, and that reference is stored in the box variable. Multiple object It is very important that you remember that the box variable does not contain the variables can contain object. It refers to the object. Two object variables can refer to the same object: references to the same object. Rectangle box2 = box; Now you can access the same Rectangle object as box and as box2, as shown in Figure 16. bjeo_ch02p.indd 46 11/29/18 3:58 PM 2.8 Object References 47 box = Rectangle box2 = x = 5 y = 10 width = 20 height = 30 © Jacob Wackerhausen/iStockphoto. Figure 16 Two Object Variables Referring to the Same Object In Java, numbers are not objects. Number variables actually store numbers. When you declare int luckyNumber = 13; then the luckyNumber variable holds the number 13, not a reference to the number (see Figure 17). The reason is again efficiency. Because numbers require little storage, it is more efficient to store them directly in a variable. luckyNumber = 13 Figure 17 A Number Variable Stores a Number Number variables You can see the difference between number variables and object variables when you store numbers. make a copy of a variable. When you copy a number, the original and the copy of the Object variables number are independent values. But when you copy an object reference, both the store references. original and the copy are references to the same object. Consider the following code, which copies a number and then changes the copy (see Figure 18): int luckyNumber = 13; ❶ int luckyNumber2 = luckyNumber; ❷ luckyNumber2 = 12; ❸ Now the variable luckyNumber contains the value 13, and luckyNumber2 contains 12. 1 luckyNumber = 13 2 luckyNumber = 13 luckyNumber2 = 13 3 luckyNumber = 13 luckyNumber2 = 12 Figure 18 Copying Numbers bjeo_ch02p.indd 47 11/21/18 5:12 PM 48 Chapter 2 Using Objects Now consider the seemingly analogous code with Rectangle objects (see Figure 19). Rectangle box = new Rectangle(5, 10, 20, 30); ❶ Rectangle box2 = box; ❷ box2.translate(15, 25); ❸ Because box and box2 refer to the same rectangle after step ❷, both variables refer to the moved rectangle after the call to the translate method. 1 box = Rectangle x = 5 y = 10 width = 20 height = 30 2 box = Rectangle box2 = x = 5 y = 10 width = 20 height = 30 3 box = Rectangle box2 = x = 20 y = 35 width = 20 height = 30 Figure 19 Copying Object References You need not worry too much about the difference between objects and object references. Much of the time, you will have the correct intuition when you think of the “object box” rather than the technically more accurate “object reference stored in variable box”. The difference between objects and object references only becomes apparent when you have multiple variables that refer to the same object. EXAMPLE CODE See sec08 of your eText or companion code for a program that demonstrates the difference between copying numbers and object references. bjeo_ch02p.indd 48 11/21/18 5:12 PM