برنامه ای که بتواند کلاس مستطیل را با ویژگی های زیر در جاوا شبیه سازی کند،
۱- هر مستطیل با مختصات دو نقطه مشخص می شود.
۲- متدهایی برای محاسبه طول و عرض و محیط و مساحت مستطیل
۳- متدهای پیشفرض مقایسه ی دو مستطیل و متد toString و equals
و …
//Rectangle Class [simple] //Java Programming //By: Sina Moradi //Website: Samiantec.ir class Rectangle { private double x1,y1,x2,y2; //Properties of a rectangle public Rectangle() //Default Constructor { setLocations(0, 0, 1, 1); } public Rectangle(double x1, double y1, double x2, double y2) //Full Constructor { setLocations(x1, y1, x2, y2); } public Rectangle(Rectangle otherRectangle) //Copy Constructor { if (otherRectangle != null) setLocations(otherRectangle.x1, otherRectangle.y1, otherRectangle.x2, otherRectangle.y2); else { System.out.println("Null Object."); System.exit(0); } } public void setLocations(double x1, double y1, double x2, double y2) //Public & Helper Method { if (x1 != x2 && y1 != y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } else { System.out.println("Invalid Rectangle."); System.exit(0); } } public double calculateWidth() //Public & Helper Method { return Math.abs(x2 - x1); } public double calculateHeight() //Public & Helper Method { return Math.abs(y2 - y1); } public double calculatePeripheral() //Public & Helper Method { return 2 * (calculateHeight() + calculateWidth()); } public double calculateArea() //Public & Helper Method { return calculateHeight() * calculateWidth(); } public boolean equals(Rectangle otherRectangle) //Public Method for compare { if (otherRectangle != null) { if (x1 == otherRectangle.x1 && x2 == otherRectangle.x2) return true; } else { System.out.println("Null Object."); System.exit(0); } return false; } public String toString() //Public Method for return object properties and ... { return "x1=" + x1 + " y1=" + y1 + " x2=" + x2 + " y2=" + y2 + " Width=" + calculateWidth() + " Height=" + calculateHeight() + " Peripheral=" + calculatePeripheral() + " Area=" + calculateArea(); } } public class Main //Rectangle Demo { public static void main(String[] args) { Rectangle r; //Reserve the variable r = new Rectangle(-1, -1, 1, 1); //Create object and let its address in variable Rectangle q=new Rectangle(r); //Reserve 'q variable' and copy 'r object' in it System.out.println(q.toString()); //Call 'toString Method' of q that return a String if (r.equals(q)) //Compare r & q with 'equals Method' of r that return a boolean System.out.println("r == q"); else System.out.println("r != q"); } }