Chapter 2: Solutions to Sample Exam Questions

Short Answer Questions

2.1. Throttle quiz = new Throttle(100);

quiz.shift(50);

System.out.println(quiz.getFlow( ));

2.2. public class Throttle

{

public Throttle(int size)... // C

public double getFlow( )... // A

public boolean isOn( )... // A

public void shift(int amount)... // M

public void shutOff( )... // M

}

2.3. A no-arguments constructor is a constructor with no parameters in its

parameter list. Under most situations,

if you write a class with no constructors, then Java

automatically creates a simple no-arguments constructor.

The automatic no-arguments constructor initializes each instance

variable to its initialization value (if there is one) or to its

default value (if there is no initialization value).

2.4. Since the new operator is called only once, there is only one Throttle

created. Both x and y refer to this one Throttle, and it has been

shifted up to position 50 out of 100. Therefore, both println

statments will print 0.5.

2.5. import edu.colorado.simulations.Throttle;

2.6. Start in some directory that is part of your CLASSPATH. Underneath this

directory, create a subdirectory edu. Underneath edu, create a

subdirectory colorado. Underneath colorado, create a subdirectory

simulations. Put Throttle.class in the simulations subdirectory.

2.7. A static method is appropriate when the method is not to be activated

by any one object. An example is the distance method in Section 2.4,

which is activated by Location.distance(p,q), with two Location

parameters p and q.

2.8. The parameter spot is initialized to refer to the same Location that

the argument s refers to. Therefore, this location's x-coordinate is

shifted by +2 along the x-axis, and s.getX( ) is then 42.

2.9. The parameter spot is initialized to the value 40 from the argument s.

But after this initialization, there is no further contact between the

parameter spot and the argument s (because int is one of the primitive

Java types and not an object). Therefore, changes to spot do not alter

s and the value of s remains 40.

2.10. The == operation tests to see whether two reference variables refer to

the same object. The equals method tests to see whether two objects

have the same values.

a==b false

a.equals(b) true

a==c false

a.equals(c) true

b==c true

b.equals(c) true

2.11. The b Location is created as a separate copy of the a Location.

Subsequent operations to b do not effect a, nor vice versa.

Therefore, a.getX( ) remains 10, but b.getX( ) shifts to 13.

2.12. Put the phrase "Implements Cloneable" in the class head.

2.13. By activating super.clone( ) inside a try-catch clause.

Multiple Choice Questions:

2.1 A 2.6 A 2.11 A

2.2 D 2.7 B 2.12 B

2.3 D 2.8 A

2.4 C 2.9 B

2.5 C 2.10 C