AN INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING WITH JAVA™, FIFTH EDITION Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of the Americas, New York, NY 10020. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of The McGraw-Hill Companies, Inc., including, but not limited to, on any network or other electronic storage or transmission, or broadcast for distance learning purposes.
Key Changes in the 5th Edition
We use the object-first approach where objects are used from the first sample program. Students first learn how to use objects and then learn how to define their own objects.
Book Organization
The key topics covered in this chapter are constructors, visibility modifiers (public and private), local variables, and passing data to methods. The use of the Scanner class for importing data from a text file is also illustrated in this chapter.
Hallmark Features of the Text
Problem Solving
Sample Development
Object-Oriented Approach
Illustrative Diagrams
Student Pedagogy
Supplements for Instructors and Students
Acknowledgments
Personal Story
- A History of Computers
- Computer Architecture
- Programming Languages
- Java
The most famous internet is simply called the internet. The Internet makes the sharing of global information possible and easy. The C++ programming language was developed as a successor to C in the early 1980s to add support for object-oriented programming.
Review Exercises
Classes and Objects
We will use the notation shown in Figure 1.1 throughout the book to represent an object. We use a rectangle to represent an object and place the underlined name of the object inside the rectangle.
Messages and Methods
The diagram in Figure 1.4 illustrates one-way communication; that is, an object performs the required operation (it walks the specified distance) but does not respond to the sender of the message. The getMaximumSpeedshown class method in Figure 1.6 returns the maximum possible speed of all Robot objects.
Class and Instance Data Values
Because the objects of a class are underlined and the data values of the class are accessible to all objects of the class, we also underline the data value of the class to demonstrate this relationship. To understand the importance of a class data value, let's see what happens when we represent the minimum balance as an instance data value.
Inheritance
The flip side of using a very powerful tool is that if we don't use it properly, we can end up in a much worse situation than if we didn't use it. In Chapter 2, for example, we will introduce many classes that come with the Java system.
Software Engineering and Software Life Cycle
The five main phases of the software life cycle are analysis, design, coding, testing and operation. We will develop an example application program in Section 2.4 following the design, coding, and testing phases of the software life cycle.
The First Java Program
An object declaration specifies the name of an object and the class to which the object belongs. Since it is case sensitive, you can use robots as the name of an object of the Robot class.
Program Components
The import statement allows the program to reference classes defined in the designated package without using the fully qualified class name. Importing a package is just shorthand for referencing classes. The only effect of importing a package is to eliminate the requirement to use the fully qualified name.
Edit-Compile-Run Cycle
Many compilers require you to create a project file and then place the source file in the project file to compile the source file. This translated version is called bytecode, and a bytecode file is a bytecode file. The name of the bytecode file generated by the compiler will have a .class suffix, while its prefix is the same as that of the source file.
If the sample program contains no syntax errors, then instead of the error message vi. When using an advanced Java IDE such as Eclipse (www.eclipse.org) or NetBeans (www.netbeans.org), you do not need to explicitly perform the compile step. Its powerful editor constantly monitors your source code as you type and highlights any mistakes.
Sample Java Standard Classes
- Standard Output
- Date and SimpleDateFormat
- Standard Input
When a program calculates a result, we need a way to display that result to the user of the program. One of the most common ways to do this in Java is to use the console window. The actual appearance of the console window will vary depending on which Java development tool we are using.
Because the actual appearance of the console window is different depending on the Java development tool you use, we use a generic picture for the console window in the diagrams. If we want to display what day of the week today is, we can use the letter Eas in Date today;. System.in is an instance of the InputStream class that only provides a facility to input 1 byte at a time with its read method.
Bad Ver sion
Sample Development —continued
Finally, we will use these classes from the main class, which we will call Ch2Monogram. String The class is used for string manipulation and extracts initials from first, middle and last names. Although we will not see any changes to this design document because this example application is very simple, changes to the design document are expected as the programs we develop become larger and more complex.
The draft document is really a working document that we will modify and expand as we progress through the development stages. Before we can actually start our development, we need to outline the steps we will follow to develop the program. There is more than one possible sequence of steps to develop a program, and the number of possible sequences will increase as the program becomes more complex.
Development: Getting Input
Note that the decision to enter the full name using one dialog box makes our job as a programmer a little more difficult, because we have to extract the first, middle and last names from a single string. In the first approach, since we get the first, middle and last names separately, that is not necessary. However, it is important to remember that we are developing the program for the benefit of the users, and not for ourselves.
In the code, notice the use of the output statement that prints the string entered by the user. After the program is written, we test the program to verify that the program works as planned. Successful execution of this program verifies that the program configuration is correct, the necessary packages have been imported, and the objects are correctly declared.
Development: Computing and Displaying the Monogram
- Variables
- Arithmetic Expressions
- Constants
- Displaying Numerical Values
- Getting Numerical Input
- The Math Class
- Random Number Generation
- Sample Development —continued
Experiment to see how the two arguments in the setLocation method affect the position of the window. In addition to the six numeric data types, there are two non-numeric basic data types. The boolean data type is used to represent the two logical values true and false. For example statements. For example, if the data type of a and bi is int, then the result of the expression is
In other words, we want to 'lock' the assigned value so that no changes can occur. When we use the literal constant 2, the data type of the constant is set to int by default. For the numeric input values, we use an equivalent method that matches the data type of the value we are trying to input.
Note that we are using here the more concise expression "java.util.Date class" to refer to a class from a specific package instead of the longer expression. History texts will say something like "the document was officially adopted on July 4, 1776, on a bright but cold Philadelphia day," but never the day of the week.
Development: Input Three Data Values
We simply chose to implement the input routine before the output routine because input comes into the program before output. For example, people don't think of interest rates in fractional values like 0.07. When the user enters an invalid value, for example an input string value that cannot be converted to a numeric value or that is converted to a negative number, the program should respond accordingly, for example by printing an error message.
We do not yet have enough skills to implement such a robust program, so we will make the following assumptions: (1) The input values are nonnegative numbers, and (2) the loan period is an integer. One important goal of this step is to verify that the input values are read in correctly by the program. To verify that the input routine is working correctly, we run the program several times and input different sets of data.
Development: Output Values
To verify that the exit routine is working correctly, we run the program and check the layout. We probably need to run the program several times to fine-tune the arguments to the println methods until we get a layout that looks clean and nice on the screen.
Development: Compute Loan Amount
Please read problem 26 on page 147 for information on how the monthly interest rate is derived from a given annual interest rate. After the program is coded, we must run the program through a series of tests. Since we assumed that the input values must be valid, we only test the program for valid input values.
If we don't make that assumption, we need to test whether the program responds correctly when invalid values are entered. To check if this program produces correct results, we can run the program with the following input values.
Development: Finishing Up
- Numerical Representation (Optional)
- First Example: Defining and Using a Class
- Second Example: Defining and Using Multiple Classes
- Matching Arguments and Parameters
- Passing Objects to a Method
- Constructors
Determine the value for each of the following expressions, or explain why it is not a valid expression. Define symbolic constants for ME and G. The distance to the Hubble Space Telescope from the center of the Earth, for example, is about 6.98 106m. For the file name we will use the name of the class followed by the java suffix.
Use the class name followed by the suffix java as the file name. But before we give the method definitions, we need to consider the data members of the Bicycle class. GetOwnerNamemethod returns a string value—the value of the ownerName instance variable—so its return type is declared as String.
From now on, we will use the name of the main class to refer to the entire program. In fact, it is possible to include all three constructors in the Account class definition.