Create a class named MyRectangle to represent rectangles. The required data fiel
ID: 3600985 • Letter: C
Question
Create a class named MyRectangle to represent rectangles. The required data fields are width, height, and color. Use double data type for width and height, and a String for color. Suppose that all rectangles are the same color. Use a static variable for color. You will need to provide the accessor methods for the properties and a method findArea() for computing the area of the rectangle.
The outline of the class is given as follows:
public class MyRectangle{
private double width = 1.0;
private double height = 1.0;
private static String color = "white";
public MyRectangle(){ }
public MyRectangle(double widthParam, double heightParam, String colorParam){ }
public double getWidth(){ }
public void setWidth(double widthParam){ }
public double getHeight(){ }
public void setHeight(double heightParam){ }
public String getColor(){ }
public static void setColor(String colorParam){ }
public double findArea(){ }
}
Write a program to test your class MyRectangle. In the client program, create two MyRectangle objects. Assign a width and height to each of the two objects. Assign the first object the color red, and the second, yellow. Display all properties of both objects including their area.
Explanation / Answer
package MyRectangle; public class MyRectangle{ private double width = 1.0; private double height = 1.0; private static String color = "black"; public MyRectangle(double par, double par1){ width ++; height ++; } //Parameters for width, height, and color // public MyRectangle(double widthParam, double heightParam, String colorParam){ width = widthParam; height = heightParam; color = colorParam; width ++; height ++; } // Accessor width // public double getWidth(){ return width; } public void setWidth(double widthParam){ width = (widthParam >= 0) ? widthParam: 0; } // Accessor height // public double getHeight(){ return height; } public void setHeight(double heightParam){ height = (heightParam >= 0) ? heightParam: 0; } // Accessor color // public static String getColor(){ return color; } public static void setColor(String colorParam){ color = colorParam; } // Accessor area // public double findArea(){ return width * height; } } class MyRectangleTest { @SuppressWarnings("static-access") public static void main(String args[]) { // Create triangle and set color value to red // MyRectangle r1 = new MyRectangle(5.0, 25.0); r1.setColor("Red"); System.out.println(r1); System.out.println("The area of rectangle one is: " + r1.findArea()); // Create triangle and set color value to yellow // MyRectangle r2 = new MyRectangle(3.0, 9.0); r2.setColor("Yellow"); System.out.println(r2); System.out.println("The area of rectangle one is: " + r2.findArea()); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.