Page 240 - Introduction to Programming with Java: A Problem Solving Approach
P. 240
206 Chapter 6 Object-Oriented Programming
Let’s review. Here’s how we declared a gus reference variable, instantiated a Mouse object, and as-
signed the object’s address to gus:
declaration
Mouse gus;
gus = new Mouse();
instantiation and assignment
Now here’s how to do the same thing with only one statement:
Mouse gus = new Mouse();
initialization
The above statement is what appears in Figure 6.5’s MouseDriver class. It’s an initialization. As men- tioned previously, an initialization is when you declare a variable and assign it a value, all in one statement.
Calling a Method
After you instantiate an object and assign its reference to a reference variable, you can call/invoke an in- stance method using this syntax:
<reference-variable>.<method-name>(<comma-separated-arguments>); Here are three example instance method calls from the MouseDriver class:
gus.setPercentGrowthRate(growthRate);
gus.grow();
gus.display();
Apago PDF Enhancer
Note how the three method calls mimic the syntax template. The first method call has one argument and the next two method calls have zero arguments. If we had a method with two parameters, we’d call it with two arguments separated by a comma.
When a program calls a method, it passes control from the calling statement to the first execut- able statement in the called method. For example, when the MouseDriver’s main method calls the setPercentGrowthRate method with gus.setPercentGrowthRate(growthRate), control passes to this statement in the Mouse class’s setPercentGrowthRate method:
this.percentGrowthRate = percentGrowthRate;
Go back to Figure 6.4’s Mouse class and verify that the setPercentGrowthRate method contains the above statement.
After the last statement in any called method executes, control returns to the calling method at the point just after where the call was made. For a pictorial explanation, see Figure 6.7.
6.5 Calling Object, this Reference
Suppose you have two objects that are instances of the same class. For example, gus and jaq refer to two objects that are instances of the Mouse class. And suppose you want the two objects to call the same instance method. For example, you want both gus and jaq to call setPercentGrowthRate. For each method call, the Java Virtual Machine (JVM) needs to know which object to update (if gus calls setPercentGrowthRate, then the JVM should update gus’s percentGrowthRate; if jaq calls