Java Reference
In-Depth Information
Suppose you were asked to write a Java class that defined the location
of pixel objects and that this class is to have methods to display the loca-
tion of a pixel and to calculate the mid-position between two pixels. One
possible option in this case is that the method to calculate the mid-point
between two pixels could receive pixel objects as parameters. The class
can be coded as follows:
class Pixel
{
// Pixel location attributes
private int x;
// x coordinate
private int y;
// y coordinate
// Constructor
public Pixel(int pixX, int pixY)
{
this.x = pixX;
this.y = pixY;
}
// Method to calculate the mid point between two pixels
public static Pixel midPix(Pixel p1, Pixel p2)
{
int midX = (p1.x/2) + (p2.x/2);
int midY = (p1.y/2) + (p2.y/2);
Pixel midOne = new Pixel(midX, midY);
return midOne;
}
// Display the address of a pixel
public void pixLocation()
{
System.out.print("Pixelx:"+this.x + " ");
System.out.print("Pixely:"+this.y + "\n\n");
System.out.flush();
}
}
Note that the method midPixel() receives two pixel objects as parame-
ters. midPixel() returns the result in a pixel object instantiated in the
class. The objects passed as parameters are known under the aliases p1
and p2. The method uses the x and y coordinates of p1 and p2 to calculate
the mid point. The program Pixels.java, listed below, demonstrates the
processing of objects passed and returned to methods.
On the Web
The source file for the program Pixels.java can be found in the Chap-
ter17folderat www.crcpress.com .
Search WWH ::




Custom Search