Since our fillCircle method always fills circles of same size in the center of the
board, it would be nice if we could have it draw different size circles
centered at an x-y coordinate that we specify. This is exactly what parameters accomplish
for us. The three parameters that we
would need are the radius, and the x- and y- coordinates, all of which we
specify in the method header. The
method invocation, correspondingly, would now include 3 arguments to
match the three parameters: Board b
= new Board(50,50); // now
fill circle with radius 10 centered at coordinate (25,30) b.fillCircle(10, 25, 30); With the
three parameters that we specified, fillCircle looks like: // this code
would go in the Board class definition in BaseBoard.java public void fillCircle(int radius, int xOrigin, int yOrigin) { //
obtain the board object’s dimensions int rows = this.getRows(); int cols = this.getCols(); for (int y = 0; y < rows; y++) { for (int x = 0;
x < cols; x++) {
if ((y – yOrigin)*(y - yOrigin) +
// condition continued (x
– xOrigin)*(x – xOrigin)
<= radius*radius)
this.fillCell(x, y, Color.red); } } } The relationship
between arguments in a method invocation and parameters in its header is key to understanding how methods work. When the statement b.fillCircle(10, 25, 30) executes, Java copies the values of the arguments 10,
25, and 30 to the parameters in the method header radius, xOrigin,
yOrigin, respectively. The parameters act as variables that are
local to the method. Next, the
statements inside fillCircle
execute. Finally when the method is
finished, the statement after b.fillCircle(10, 25, 30) executes. Keep in mind
that the method invocation and the method implementation are in different
files. // Method
invocation in CircleTest.java copies the values of
the arguments to the parameters
// Method
definition in BaseBoard.java public void fillCircle(int radius, int xOrigin, int yOrigin) //
Inside fillCircle, the value of radius is 10, //
xOrigin 25, and yOrigin
30 There’s important things to
recognize here. We now have two
methods both named the same thing (fillCircle), but each takes on a different
number of parameters. In programming
language terms, this is referred to as method
overloading. A method is
overloaded when we define it two or more times (with the same method name),
but each of the definitions has a different signature (go back and look up
what signature means). This is
convenient since we can draw square differently by specifying or not
specifying parameters, but the method name is the same. |