The above example did not explain how to model the declaration of local variables. Recall that local variables may be introduced by statements like:
int a = (x + width)/2; Polygon p = new Polygon(); Color cb = c.brighter();
To illustrate the handling of local variables, let's modify the Hole1 class to make its structure clearer.
import java.awt.*; import java.applet.Applet; public class Hole2 extends Applet { public void paint(Graphics g) { this.drawHole(g, 50); this.drawHole(g, 25); } public void drawHole(Graphics g, int rad) { // Draw a yellow circle with radius rad at point (60,80) inscribed in a blue square. this.drawHoleAt(g, 60, 80, rad); } public void drawHoleAt(Graphics g, int x, int y, int rad) { // Draw a yellow circle with radius rad at point (x,y) inscribed in a blue square. this.fillSquare(g, x-rad, y-rad, 2*rad, Color.blue); this.fillCircle(g, x, y, rad, Color.yellow); } public void fillSquare(Graphics g, int x, int y, int side, Color clr) { // Fill with color clr a square whose upper left corner is (x, y) // and whose side length is side. g.setColor(clr); g.fillRect(x, y, side, side); } public void fillCircle(Graphics g, int x, int y, int rad, Color clr) { // Fill with color clr a circle with center point (x, y) and radius rad. int side = 2* rad; g.setColor(clr); g.fillOval(x-rad, y-rad, side, side); } }
The above Hole2 class draws the same logo as the Hole1 class, but uses the extra methods drawHoleAt, fillSquare, and fillCircle. fillCircle uses the declaration int side = 2 * rad to introduce a local variable side that is twice the radius rad. When the red control dot encounters a declaration like this, it adds a new variable name side to the set of variables of the local execution frame for fillCircle.The execution tree that results from sending a paint message to Hole2 instance H2 with argument G2 is shown below in table form. Pay particular attention to the extra side variables in the frame for fillCircle.
H2.paint(G2); |
|