有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用stoplight示例对调用的方法进行java澄清

下面的代码出现在我的书中关于方法的章节中。有几件事我有点困惑

  1. 当我相信run()方法正在调用createFilledCircle方法时,我的理解正确吗
  2. run()方法是接收者,而createFilledCircle方法是发送者吗
  3. 对于三个add(createFilledCircles...red,yellow and green);程序员如何知道参数中允许哪些信息?在add(createFilledCircle)中是否使用了(x location, y location, width of figure, height of figure)的格式


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; 
}

共 (2) 个答案

  1. # 1 楼答案

    1) Is my understanding correct when I believe that the run() method is calling the createFilledCircle method?

    2) Is the run() method the receiver and the createFilledCircle the sender?

    我不知道你说的“接收者”和“发送者”是什么意思。这些不是人们在谈论被调用的方法时通常使用的术语

    (它看起来像是Smalltalk编程语言中的术语,Smalltalk编程语言是一种早期的面向对象语言。鉴于此,它正好相反:你会说run是发送方createFilledCircle是接收方。)

    3) 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 the add(createFilledCircle)?

    createFilledCircle方法的声明指定了该方法需要的参数:三个double值和一个Color

    在这样一行中:

    add(createFilledCircle(cx, cy-dy, LAMP_RADIUS, Color.RED));
    

    发生的情况是,首先使用参数cx, cy-dy, LAMP_RADIUS, Color.RED调用createFilledCircle,然后将方法createFilledCircle的返回值(即GOval值)传递给add方法。与此相同:

    GOval result = createFilledCircle(cx, cy-dy, LAMP_RADIUS, Color.RED);
    add(result);
    
  2. # 2 楼答案

    1)是的——它在

    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));
    

    2)它是发送方,但add()方法是接收方

    3)createFilledCircle已使用

    createFilledCircle (double x, double y, double r, Color color)