The rectangle class was defined as:
public class Rectangle
{
private double width, height;
public Rectangle()
{
// initialise instance variables
width = 1;
height = 1;
}
public Rectangle(double w, double h)
{
// initialise instance variables
width = w;
height = h;
}
public double getArea()
{
// put your code here
return width*height;
}
public void setWidth(double w)
{
width = w;
}
public void setHeight(double h)
{
height = h;
}
}
|
We want to allow the user to create a Rectangle object using another rectangle object, like this:
Rectangle r1 = new Rectangle(w, h); // creates a rectangle with width=w and height=h
Rectangle r2 = new Rectangle( r1 ); // create r2 as a copy of r1
|
Add the necessary code to the Rectangle class above to make it work.
Use the following myProg class to test the new Rectangle class that you write for this assignment:
public class myProg
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(2,3);
System.out.println("Area of r2 = " + r1.getArea() );
Rectangle r2 = new Rectangle( r1 );
System.out.println("Area of r2 = " + r2.getArea() );
r2.setWidth(4);
System.out.println("Area2 of r2 = " + r2.getArea() );
r2.setHeight(5);
System.out.println("Area3 of r2 = " + r2.getArea() );
}
}
|
If your Rectangle class is correct, the output of the test program will be:
Area of r2 = 6.0 Area of r2 = 6.0 Area2 of r2 = 12.0 Area3 of r2 = 20.0 |