/* * Created on Sep 5, 2003 * */ public class Rectangle { // instance variables: private int x1, y1, x2, y2; // upper left and lower right corners private int width, height; // constructor: public Rectangle(int x, int y, int width, int height) { x1 = x; y1 = y; x2 = x+width; y2 = y+height; this.width = width; this.height = height; } // overriding the toString method defined in the class Object: public String toString() { return "a " + width + "x" + height + " rectangle at " + "(" + x1 + "," + y1 + ")"; } public int getX() { return x1; } public int getY() { return y1; } public int getWidth() { return width; } public int getHeight() { return height; } public int area() { return width * height; } public double diagonal() { return Math.sqrt(Math.pow(width,2)+Math.pow(height,2)); } public boolean containsPoint(int x, int y) { return (x1 <= x) && (x <= x2) && (y1 <= y) && (y <= y2); } private boolean hasNegativeDimension() { return width < 0 || height < 0; } private Rectangle getIntersection(Rectangle r) { int left = Math.max(x1,r.x1); int right = Math.min(x2,r.x2); int top = Math.max(y1,r.y1); int bottom = Math.min(y2,r.y2); Rectangle result = new Rectangle(left, top, right-left, bottom-top); if (result.hasNegativeDimension()) result = EMPTY; return result; } } public class TestProgram { public static void main(String args[]) { Stytem.out.println("Starting the test program..."); Rectangle r = new Rectangle(10,25,50,100); System.out.println("r is " + r); // implicitly calls toString Stytem.out.println("...done."); } } The output from this program would be: Starting the test program... r is a 50x100 rectangle at (10,25) ...done.