6. Methods: Communicating with Objects

6.9. DrawingLinesandDefiningGraphical Methods (Optional)

 

We used a Graphics object in the previous chapter to draw rectangles and ovals in a JFrame window. The Graphics class also possesses a method for drawing a line segment. Problems involving drawing pic- tures in an JFrame window using a series of line segments can be a source of examples of defining useful methods and also of making good use of loops.

The Graphics class has a public instance method with the header:

,,

 

J

The method call g.drawLine(x1, y1, x2, y2) draws a line from the point (x1, y1) to (x2, y2) where (x, y) refers to a point that is x pixels from the left edge of the area that g is drawing in and y pixels from the top edge. Thus g.drawLine(10, 10, 10, 60) draws a vertical line segment that is 50 pixels long and is 10 pixels from the left edge of the drawing area, that is, a line segment from the point (10, 10) to the point (10, 60).

Consider the problem of creating an Swing program with a method called drawSticks() to draw any specified number of vertical line seg- ments. This method might be useful for an graphical user interface to the OneRowNim game to draw the number of sticks at a given point in a game. Suppose that this method must have an int parameter to specify the number of vertical lines to draw and two int parameters to spec- ify the location of the top endpoint of the left most line segment. The drawSticks() method will need to use a Graphics object connected to the JFrame window for drawing the line segment. The only such Graphics object available is the parameter in the paint() method of the Canvas. Thus the method must have a Graphics parameter and it will be called in the paint() method using the Graphics object there as an argument. Thus the header of the method should look like:

,,

 

J

The length of the line segments and and the distance between them are not specified by parameters so we need to choose some fixed values for these quantities. Let us assume that the line segments are 10 pixels apart and 50 pixels long. We now have enough information to complete the definition of an applet to solve this problem. Such a class definition is reproduced in Figure 3.19.

Note that the body of drawSticks() uses a while-loop to draw the lines and declares and initializes a local variable to zero to use for counting the number of lines drawn. The statement g.drawLine(x, y, x, y + 50); draws a vertical line which is 50 pixels long. Increasing the value of x by 10 each time through the loop moves the next line 10 pixels to the right.

The first call to drawSticks() in the paint() method draws 12

lines with (25, 25) the top point of the left-most line. The second call to

 

CHAPTER 3 Chapter Summary139

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 3.19: A Swing Class with a method for drawing a set of sticks.

 

 

drawSticks() will draw 7 cyan sticks 100 pixels lower. Note that chang- ing the color of g before passing it as an argument to drawSticks() changes the drawing color.

An image of the DrawSticksCanvas as it appears in a window is shown in Figure 3.20.

As we have seen in this example, defining methods with parameters to draw an object makes the code reusable and makes it possible to draw a complex scene by calling a collection of simpler methods. It is a typical use of the divide-and-conquer principle. The while-loop can be useful in drawing almost any geometrically symmetric object.

 

 

Technical Terms


 

Figure 3.20: The DrawSticksCan- vas as displayed in a Java win- dow.

CHAPTER SUMMARY

 

accessor method class scope formal parameter if statement if/else statement inherit

local scope


loop structure method overloading method signature mutator method multiway selection override polymorphism


repetition structure scope

selection side effect

while statement while structure

 

 

Summary of Important Points

A formal parameter is a variable in a method declaration. It always con- sists of a type followed by a variable identifier. An argument is a value that is passed to a method via a formal parameter when the method is invoked. A method’s parameters constrain the type of information that can be passed to a method.

When an argument of primitive type is passed to a method, it cannot be modified within the method. When an argument of reference type is passed to a method, the object it refers to can be modified within the method.

Except for void methods, a method invocation or method call is an expression which has a value of a certain type. For example, nim.getSticks() returns a int value.

The signature of a method consists of its name, and the number, types, and order of its formal parameters. A class may not contain more than one method with the same signature.

A constructor is a method that is invoked when an object is created. If a class does not contain a constructor method, the Java compiler supplies a default constructor.

Restricting access to certain portions of a class is a form of informa- tion hiding. Generally, instance variables are hidden by declaring them private. The class’s public methods make up its interface.

The if statement executes a statement only if its boolean condition is

true. The if-else statement executes one or the other of its statements depending on the value of its boolean condition. Multiway selection al- lows one and only one of several choices to be selected depending on the value of its boolean condition.

The while statement is used for coding loop structures that repeatedly execute a block of code while a boolean condition is satisfied.

 

 

 

 

 

SOLUTIONS TO

SELF-STUDY EXERCISES


SOLUTION 3.1 A method declaration defines the method by specifying its name, qualifiers, return type, formal parameters, and its algorithm, thereby associating a name with a segment of executable code. A method invocation calls or uses a defined method.

 

SOLUTION 3.2 A formal parameter is a variable in the method declaration, whose purpose is to store a value while the method is running. An argument is a value that is passed to a method in place of a formal parameter.

 

CHAPTER 3 Solutions to Self-Study Exercises141

SOLUTION 3.3 The following code declares two instance variables for names of players and defines a setName() method:

,,

 

 

 

 

 

J

Of course, there are many other appropriate names for the variables and parame- ters and other initial assignments.

 

SOLUTION 3.4 A method call that sets the names of the players of game1 is:

,,

 

J

 

SOLUTION 3.5 A constructor cannot have a return type, such as void.

 

SOLUTION 3.6 One definition for the method is:

,,

 

 

 

J

 

SOLUTION 3.7 The following would be displayed on the screen:

,,

 

 

J

 

SOLUTION 3.8 One definition for the method is:

,,

 

 

J

 

SOLUTION 3.9 One definition for the method is:

,,

 

 

J

 

SOLUTION 3.10 See Figure 3.21.

 

Figure 3.21: Flowchart of the if- else version of the getStatus() method.

 

SOLUTION 3.11

,,

 

 

 

 

 

 

J

SOLUTION 3.12

,,

 

 

 

 

 

 

 

J

SOLUTION 3.13 When passing an argument for a primitive type, a copy of the argument’s value is passed. The actual argument cannot be changed inside the method. When passing a reference to an object, the object can be changed within the method.

SOLUTION 3.14

,,

 

 

 

 

 

 

 

J

 

 

EXERCISESEXERCISE 3.1 Fill in the blanks in each of the following sentences:

When two different methods have the same name, this is an example of

.

Methods with the same name are distinguished by their.

 

Note: For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.


A method that is invoked when an object is created is known as a

method.

 

A method whose purpose is to provide access to an object’s instance variables is known as anmethod.

A boolean value is an example of atype.

A OneRowNim variable is an example of atype.

A method’s parameters havescope.

A class’s instance variables havescope.

Generally, a class’s instance variables should haveaccess.

The methods that make up an object’s interface should haveaccess.

A method that returns no value should be declared.

Java’s if statement and if-else statement are both examples ofcontrol structures.

An expression that evaluates to either true or false is known as a.

In an if-else statement, an else clause matches.

The ability to use a superclass method in a subclass is due to Java’s

mechanism.

The process of redefining a superclass method in a subclass is known as

the method.

 

EXERCISE 3.2 Explain the difference between the following pairs of concepts:

 

Parameter and argument.

Method definition and method invocation.

Local scope and class scope.

Primitive type and reference type.

Access method and constructor method.

 

EXERCISE 3.3 Translate each of the following into Java code:

 

If b1 is true, then print “one”; otherwise, print “two”.

If b1 is false and if b2 is true, then print “one”; otherwise, print “two”.

If b1 is false and if b2 is true, then print “one”; otherwise, print “two”, or print “three”.

EXERCISE 3.4 Identify and fix the syntax errors in each of the following: a.

,,

 

 

 

J

b.

,,

 

 

 

J

 

c.

,,

 

 

 

J

d.

,,

 

 

 

J

 

 

EXERCISE 3.5 For each of the following, suppose that isWalking is true and isTalking is false (first draw a flowchart for each statement and then determine what would be printed by each statement):

 

 

a.

,,

 

 

J

b.

,,

 

 

J

c.

,,

 

 

 

J

d.

,,

 

 

 

 

 

J

 

EXERCISE 3.6 Show what the output would be if the following version of

main() were executed:

,,

 

 

 

 

 

 

 

 

 

 

J

EXERCISE 3.7 Determine the output of the following program:

,,

 

 

 

 

 

 

 

 

J

EXERCISE 3.8 Write a boolean method—a method that returns a boolean that takes an int parameter and converts the integers 0 and 1 into false and true, respectively.

EXERCISE 3.9 Define an int method that takes a boolean parameter. If the parameter’s value is false, the method should return 0; otherwise, it should return 1.

EXERCISE 3.10 Define a void method named hello that takes a single boolean parameter. The method should print “Hello” if its parameter is true; otherwise, it should print “Goodbye”.

EXERCISE 3.11 Define a method named hello that takes a single boolean parameter. The method should return “Hello” if its parameter is true; otherwise it should return “Goodbye”. Note the difference between this method and the one in the previous exercise. This one returns a String. That one was a void method.

EXERCISE 3.12 Write a method named hello that takes a single String pa- rameter. The method should return a String that consists of the word “Hello” concatenated with the value of its parameter. For example, if you call this method with the expression hello("dolly"), it should return “hello dolly”. If you call it with hello("young lovers wherever you are"), it should return “hello young lovers wherever you are”.

 

EXERCISE 3.13 Define a void method named day1 that prints “a partridge in a pear tree”.

EXERCISE 3.14 Write a Java application program called TwelveDays that prints the Christmas carol “Twelve Days of Christmas.” For this version, write a void method named intro() that takes a single String parameter that gives the day of the verse and prints the intro to the song. For example, intro("first") should print, “On the first day of Christmas my true love gave to me”. Then write methods day1(), day2(), and so on, each of which prints its version of the verse. Then write a main() method that calls the other methods to print the whole song.

EXERCISE 3.15 Define a void method named verse that takes two String parameters and returns a verse of the Christmas carol “Twelve Days of Christ- mas.” For example, if you call this method with verse("first", "a partridge in a pear tree"), it should return, “On the first day of Christ- mas my true love gave to me, a partridge in a pear tree”.

EXERCISE 3.16 Define a void method named permute, which takes three String parameters and prints out all possible arrangements of the three strings. For example, if you called permute("a", "b", "c"), it would produce the following output: abc, acb, bac, bca, cab, cba, with each permutation on a separate line.

EXERCISE 3.17 Design a method that can produce limericks given a bunch of rhyming words. That is, create a limerick template that will take any five words or phrases and produce a limerick. For example, if you call

,,

 

J

your method might print (something better than)

,,

 

 

 

J

For each of the following exercises, write a complete Java application program:

EXERCISE 3.18 Define a class named Donor that has two instance variables, the donor’s name and rating, both of which are Strings. The name can be any string, but the rating should be one of the following values: “high,” “medium,” or “none.” Write the following methods for this class: a construc- tor, Donor(String,String), that allows you to set both the donor’s name and rating; and access methods to set and get both the name and rating of a donor.

EXERCISE 3.19 Challenge. Define a CopyMonitor class that solves the fol- lowing problem. A company needs a monitor program to keep track of when a particular copy machine needs service. The device has two important (boolean) variables: its toner level (too low or not) and whether it has printed more than 100,000 pages since its last servicing (it either has or has not). The servicing rule that the company uses is that service is needed when either 100,000 pages have been printed or the toner is too low. Your program should contain a method that reports either “service needed” or “service not needed” based on the machine’s state. (Pretend that the machine has other methods that keep track of toner level and page count.)

 

EXERCISE 3.20 Challenge. Design and write an OldMacdonald class that sings several verses of “Old MacDonald Had a Farm.” Use methods to generalize the verses. For example, write a method named eieio() to “sing” the “E I E I O” part of the verse. Write another method with the signature hadAnX(String s), which sings the “had a duck” part of the verse, and a method withA(String sound) to sing the “with a quack quack here” part of the verse. Test your class by writing a main() method.

 

ADDITIONAL EXERCISES

EXERCISE 3.21 Suppose you have an Object A, with public methods a(), b(), and private method c(). And suppose you have a subclass of A named B with methods named b(), c() and d(). Draw a UML diagram showing the rela- tionship between these two classes. Explain the inheritance relationships between them and identify those methods that would be considered polymorphic.

EXERCISE 3.22 Consider the definition of the class C. Define a subclass of C named B that overrides method m1() so that it returns the difference between m and n instead of their sum.

,,

 

 

 

 

 

 

 

J

 

 

 

 

 

 

 

 

 

Chapter 4