Copy Constructor in Rectangle Class
A copy constructor is a constructor with a single argument of the same type as the class. Making a copy of an object requires a special method called a copy constructor. The copy constructor should create an object that is a separate, independent object, but with the instance variables set so that it is an exact copy of the argument object.
You will create a copy constructor in rectangle
class.
public Rectangle(Rectangle original) { upperLeft = new Point(original.upperLeft.getX(),original.upperLeft.getY()); // Finish the rest of the code for another three instance variables }
Testing
Uncommenting the last part of the test program in main. Use the same test case in step 6 to test your program.
Scanner scanner = new Scanner(System.in); int x = 1; int y = 1; System.out.print("Enter the x-coordinate of the upperLeft :"); x = scanner.nextInt(); System.out.print("Enter the y-coordinate of the upperLeft :"); y = scanner.nextInt(); Point upperLeft = new Point(x, y); System.out.print("Enter the x-coordinate of the lowerLeft :"); x = scanner.nextInt(); System.out.print("Enter the y-coordinate of the lowerLeft :"); y = scanner.nextInt(); Point lowerLeft = new Point(x, y); System.out.print("Enter the x-coordinate of the lowerRight :"); x = scanner.nextInt(); System.out.print("Enter the y-coordinate of the lowerRight :"); y = scanner.nextInt(); Point lowerRight = new Point(x, y); System.out.print("Enter the x-coordinate of the upperRight:"); x = scanner.nextInt(); System.out.print("Enter the y-coordinate of the upperRight:"); y = scanner.nextInt(); Point upperRight = new Point(x, y); Rectangle rectangle = new Rectangle(upperLeft, lowerLeft, lowerRight, upperRight); System.out.printf("Length of rectangle : %.2f\n", rectangle.getLength()); System.out.printf("Width of rectangle : %.2f\n", rectangle.getWidth()); System.out.printf("Area of rectangle : %.2f\n", rectangle.getArea()); System.out.printf("Perimeter of rectangle : %.2f\n", rectangle.getPerimeter()); //test the copy constructor Rectangle rectangleNew = new Rectangle(rectangle); System.out.printf("Length of rectangleNew : %.2f\n", rectangleNew.getLength()); System.out.printf("Width of rectangleNew : %.2f\n", rectangleNew.getWidth()); System.out.printf("Area of rectangleNew : %.2f\n", rectangleNew.getArea()); System.out.printf("Perimeter of rectangleNew : %.2f\n", rectangleNew.getPerimeter());