• 沒有找到結果。

Explicit and Implicit Method Parameters 69

BankAccount harrysChecking = new BankAccount();

harrysChecking.withdraw(30);

However, there is one situation in which it is legitimate to invoke a method without, seemingly, an implicit parameter. Consider the following modification to the BankAccount class. Add a method to apply the monthly account fee:

class BankAccount { . . .

public void monthlyFee() {

withdraw(10); // withdraw $10 from this account }

}

That means to withdraw from the same account object that is carrying out the monthlyFee operation. In other words, the implicit parameter of the withdraw method is the (invis-ible) implicit parameter of the monthlyFee method.

If you find it confusing to have an invisible parameter, you can always use the this parameter to make the method easier to read:

class BankAccount { . . .

public void monthlyFee() {

this.withdraw(10); // withdraw $10 from this account }

}

Calling One Constructor from Another

Consider the BankAccount class. It has two constructors: a constructor without param-eters to initialize the balance with zero, and another constructor to supply an initial bal-ance. Rather than explicitly setting the balance to zero, one constructor can call another constructor of the same class instead. There is a shorthand notation to achieve this result:

class BankAccount {

public BankAccount (double initialBalance) {

balance = initialBalance;

}

public BankAccount() {

this(0);

} . . . }

















Advanced Topic 2.3















The command this(0); means “Call another constructor of this class and supply the value 0.” Such a constructor call can occur only as the first line in another constructor.

This syntax is a minor convenience. We will not use it in this book. Actually, the use of the keyword this is a little confusing. Normally, this denotes a reference to the implicit parame-ter, but if this is followed by parentheses, it denotes a call to another constructor of this class.

Mainframes—When Dinosaurs Ruled the Earth

When the International Business Machines Corporation, a successful manufacturer of punched-card equipment for tabulating data, first turned its attention to designing com-puters in the early 1950s, its planners assumed that there was a market for perhaps 50 such devices, for installation by the government, the military, and a few of the country’s largest corporations. Instead, they sold about 1,500 machines of their System 650 model and went on to build and sell more powerful computers.

The so-called mainframe computers of the 1950s, 1960s, and 1970s were huge. They filled up whole rooms, which had to be climate-controlled to protect the delicate equip-ment (see Figure 13). Today, because of miniaturization technology, even mainframes are getting smaller, but they are still very expensive. (At the time of this writing, the cost for a midrange IBM 3090 is approximately 4 million dollars.)





Random Fact 2.1



F i g u r e 1 3

A Mainframe Computer

























Chapter Summary 71

These huge and expensive systems were an immediate success when they first appeared, because they replaced many roomfuls of even more expensive employees, who had previously performed the tasks by hand. Few of these computers do any exciting computations. They keep mundane information, such as billing records or airline reser-vations; they just keep lots of them.

IBM was not the first company to build mainframe computers; that honor belongs to the Univac Corporation. However, IBM soon became the major player, partially because of technical excellence and attention to customer needs and partially because it exploited its strengths and structured its products and services in a way that made it difficult for customers to mix them with those of other vendors. In the 1960s, IBM’s competitors, the so-called “Seven Dwarfs”—GE, RCA, Univac, Honeywell, Burroughs, Control Data, and NCR—fell on hard times. Some went out of the computer business alto-gether, while others tried unsuccessfully to combine their strengths by merging their computer operations. It was generally predicted that they would eventually all fail. It was in this atmosphere that the U.S. government brought an antitrust suit against IBM in 1969. The suit went to trial in 1975 and dragged on until 1982, when the Reagan Administration abandoned it, declaring it “without merit”.

Of course, by then the computing landscape had changed completely. Just as the dinosaurs gave way to smaller, nimbler creatures, three new waves of computers had appeared: the minicomputers, workstations, and microcomputers, all engineered by new companies, not the Seven Dwarfs. Today, the importance of mainframes in the market-place has diminished, and IBM, while still a large and resourceful company, no longer dominates the computer market.

Mainframes are still in use today for two reasons. They still excel at handling large data volumes. More importantly, the programs that control the business data have been refined over the last 20 or more years, fixing one problem at a time. Moving these programs to less expensive computers, with different languages and operating systems, is difficult and error-prone. Sun Microsystems, a leading manufacturer of worksta-tions, was eager to prove that its mainframe system could be “downsized” and replaced by its own equipment. Sun eventually succeeded, but it took over five years—far longer than it expected.

1. Objects are entities in your program that you manipulate by invoking methods.

2. The public interface of a class specifies what you can do with its objects. The hidden implementation describes how these actions are carried out.

3. Classes are factories for objects. You construct a new object of a class with the new operator.

4. You store object locations in object variables.

5. All object variables must be initialized before you access them.























Chapter Summary

6. An object reference describes the location of an object.

7. Multiple object variables can contain references to the same object.

8. Java classes are grouped into packages. If you use a class from another package (other than the java.lang package), you must import the class.

9. A method definition specifies the method name, parameters, and the statements for carrying out the method’s actions.

10. Use the return statement to specify the value that a method returns to its caller.

11. To test a class, use an environment for interactive testing, or write a second class to execute test instructions.

12. An object uses instance fields to store its state—the data that it needs to execute its methods.

13. Each object of a class has its own set of instance fields.

14. Encapsulation is the process of hiding object data and providing methods for data access.

15. You should declare all instance fields as private.

16. Constructors contain instructions to initialize objects. The constructor name is always the same as the class name.

17. The new operator invokes the constructor.

18. Overloaded methods are methods with the same name but different parameter types.

19. Abstraction is the process of finding the essential feature set for a class.

20. Use documentation comments to describe the classes and public methods of your programs.

21. Provide documentation comments for every class, every method, every parameter, and every return value.

22. Instance fields belong to an object. Parameter variables and local variables belong to a method—they die when the method exits.

23. Instance fields are initialized to a default value, but you must initialize local variables.

24. The implicit parameter of a method is the object on which the method is invoked.

The this reference denotes the implicit parameter.

25. Use of an instance field name in a method denotes the instance field of the implicit parameter.

Exercise R2.1. Explain the difference between an object and an object reference.

Exercise R2.2. Explain the difference between an object and an object variable.

Review Exercises

Review Exercises 73

Exercise R2.3. Explain the difference between an object and a class.

Exercise R2.4. Explain the difference between a constructor and a method.

Exercise R2.5. Give the Java code for an object of class BankAccount and for an object variable of class BankAccount.

Exercise R2.6. Explain the difference between an instance field and a local variable.

Exercise R2.7. Explain the difference between a local variable and a parameter variable.

Exercise R2.8. Explain the difference between new BankAccount(5000);

and

BankAccount b = new BankAccount(5000);

Exercise R2.9. Explain the difference between BankAccount b;

and

BankAccount b = new BankAccount(5000);

Exercise R2.10. What are the construction parameters for a BankAccount object?

Exercise R2.11. Give Java code to construct the following objects:

• A rectangle with center (100, 100) and all side lengths equal to 50

• A greeter who will say "Hello, Mars!"

• A bank account with a balance of $5000 Create just objects, not object variables.

Exercise R2.12. Repeat the preceding exercise, but now define object variables that are initialized with the required objects.

Exercise R2.13. Find the errors in the following statements:

Rectangle r = (5, 10, 15, 20);

double x = BankAccount(10000).getBalance();

BankAccount b;

b.deposit(10000);

b = new BankAccount(10000);

b.add("one million bucks");

Exercise R2.14. Describe all constructors of the BankAccount class. List all methods that can be used to change a BankAccount object. List all methods that don’t change the BankAccount object.

Exercise R2.15. What is the value of b after the following operations?

BankAccount b = new BankAccount(10);

b.deposit(5000);

b.withdraw(b.getBalance() / 2);

Exercise R2.16. If b1 and b2 store objects of class BankAccount, consider the following instructions.

b1.deposit(b2.getBalance());

b2.deposit(b1.getBalance());

Are the balances of b1 and b2 now identical? Explain.

Exercise R2.17. What is the this reference?

Exercise R2.18. What does the following method do? Give an example of how you can call the method.

public class BankAccount {

public void mystery(BankAccount that, double amount) {

this.balance = this.balance - amount;

that.balance = that.balance + amount;

}

. . . // other bank account methods }

Exercise P2.1. Write a program that constructs a Rectangle object, prints it, and then translates and prints it three more times, so that, if the rectangles were drawn, they would form one large rectangle:

Exercise P2.2. The intersection method computes the intersection of two rectangles—

that is, the rectangle that is formed by two overlapping rectangles:

Programming Exercises

Intersection

Programming Exercises 75

You call this method as follows:

Rectangle r3 = r1.intersection(r2);

Write a program that constructs two rectangle objects, prints them, and then prints the rectan-gle object that describes the intersection. What happens when the rectanrectan-gles do not overlap?

Exercise P2.3. Add a method sayGoodbye to the Greeter class.

Exercise P2.4. Add a method refuseHelp to the Greeter class. It should return a string such as "I am sorry, Dave. I am afraid I can't do that."

Exercise P2.5. Write a program that constructs a bank account, deposits $1000, with-draws $500, withwith-draws another $400, and then prints the remaining balance.

Exercise P2.6. Add a method

void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statements BankAccount momsSavings = new BankAccount(1000);

momsSavings.addInterest(10); // 10% interest the balance in momsSavings is $1,100.

Exercise P2.7. Write a class SavingsAccount that is similar to the BankAccount class, except that it has an added instance variable interest. Supply a constructor that sets both the initial balance and the interest rate. Supply a method addInterest (with no explicit parameter) that adds interest to the account. Write a program that constructs a savings account with an initial balance of $1,000 and interest rate 10%. Then apply the addInterest method five times and print the resulting balance.

Exercise P2.8. Implement a class Employee. An employee has a name (a string) and a salary (a double). Write a default constructor, a constructor with two parameters (name and sal-ary), and methods to return the name and salary. Write a small program that tests your class.

Exercise P2.9. Enhance the class in the preceding exercise by adding a method raiseSalary (double byPercent) that raises the employee’s salary by a certain percentage. Sample usage:

Employee harry = new Employee("Hacker, Harry", 55000);

harry.raiseSalary(10); // Harry gets a 10% raise

Exercise P2.10. Implement a class Car with the following properties. A car has a certain fuel efficiency (measured in miles/gallon or liters/km—pick one) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor, and the initial fuel level is 0. Supply a method drive that simulates driving the car for a certain distance, reduc-ing the fuel level in the gas tank, and methods getGas, returning the current fuel level, and addGas, to tank up. Sample usage:

Car myBeemer = new Car(29); // 29 miles per gallon myBeemer.addGas(20); // tank 20 gallons

myBeemer.drive(100); // drive 100 miles System.out.println(myBeemer.getGas());

// print fuel remaining

相關文件