The code below appears in my book in the chapter about Methods. I’m a little confused about a couple of things.
- Is my understanding correct when I believe that the
run()method is calling thecreateFilledCirclemethod? - Is the
run()method the receiver and thecreateFilledCirclethe sender? - for the three
add(createFilledCircles...red,yellow and green);how does the programmer know what information is permitted in the argument? Is the format of(x location, y location, width of figure, height of figure)being used in theadd(createFilledCircle)?
import acm.program.*;
import acm.graphics.*;
import java.awt.*;
public class StopLight extends ConsoleProgram {
public void run() {
double cy = getWidth() / 2 ;
double cx= getHeight() / 2;
double fx = cx - (FRAME_WIDTH / 2);
double fy = cy - (FRAME_HEIGHT /2 );
double dy = (FRAME_HEIGHT / 4 ) + (LAMP_RADIUS / 2);
GRect frame = new GRect (fx, fy, FRAME_WIDTH, FRAME_HEIGHT);
frame.setFilled(trye);
frame.setColor(Color.GRAY);
add(frame);
add(createFilledCircle(cx, cy-dy, LAMP_RADIUS, Color.RED));
add(createFilledCircle(cx, cy, LAMP_RADIUS, Color.YELLOW));
add(createFilledCircle(cx, cy + dy, LAMP_RADIUS, Color.GREEN));
}
private GOval createFilledCircle (double x, double y, double r, Color color) {
GOval circle = new GOval (x -r, y -r, 2 * r, 2 * y );
circle.setFilled(true);
circle.setColor(color);
return circle;
}
private static final double FRAME_WIDTH = 50;
private static final double FRAME_HEIGHT = 100;
private static final LAMP_RADIUS = 10;
}
Yes.
I don’t know what you mean by “receiver” and “sender”. Those are not terms that people normally use when talking about methods being called.
(It looks like teminology from the Smalltalk programming language, which was an early object oriented language. In the light of that, it’s exactly the other way around: you’d say
runis the sender andcreateFilledCircleis the receiver.)The declaration of the
createFilledCirclemethod specifies what parameters that method needs: threedoublevalues and aColorvalue.In a line such as this one:
what happens is that
createFilledCircleis called first, with the argumentscx, cy-dy, LAMP_RADIUS, Color.RED, and then the return value of the methodcreateFilledCircle, which is aGOvalvalue, is passed to theaddmethod. It’s the same as this: