Okay so I have a rectangle class having the default values for the rectangle'd height, width and color and area. Everything is working fine when I test them in my Test Class except the color.
Suppose I create two rectangle objects in test class, r1 and r2, I can find the area with different values easily and print them out, but for color, its only showing me the color of r2, If I remove object r2 and keep r1 only then I can see the color name of my object r1; otherwise its showing me the color of r2 in both r1 and r2 when I print them out. Code and output is below
Rectangle Class
public class Rectangle { private double width = 1; private double height = 1; private static String color = "white"; public Rectangle (double newWidth, double newHeight, String newColor ) { setWidth(newWidth); setHeight(newHeight); setColor(newColor); } public double getWidth ( ) { return width; } public void setWidth ( double newWidth ) { if (newWidth <= 0) { System.out.println("Fatal error"); System.exit(0); } else { width = newWidth; } } public double getHeight ( ) { return height; } public void setHeight ( double newHeight ) { if (newHeight <= 0) { System.out.println("Fatal error"); System.exit(0); } else { height = newHeight; } } public String getColor ( ) { return color; } public void setColor ( String newColor ) { color = newColor; } public double findArea ( ) { double area = width * height; return area; } public String toString ( ) { return ("Deafult height " + height + "Default width " + width + "Default color " + color); } }
Test Class
public class TestClass { public static void main(String[] args){ //invoking parameterized constructor Rectangle r1 = new Rectangle(7, 6, "red"); double area1 = r1.findArea(); Rectangle r2 = new Rectangle(9, 5, "yellow"); double area2 = r2.findArea(); //printing properties of the rectangles r1 and r2 System.out.println("Properties of the First Rectangle \'r1\' " + "\n"+ "Color: " + r1.getColor() + "\n" + "Height: " + r1.getWidth() + "\n" + "Width " + r1.getHeight() + "\n" + "Area: " + area1 + "\n"); System.out.println("Properties of the Second Rectangle \'r2\' " + "\n"+ "Color: " + r2.getColor() + "\n" + "Height: " + r2.getWidth() + "\n" + "Width " + r2.getHeight() + "\n" + "Area: " + area2 + "\n"); } }
Output
Properties of the First Rectangle 'r1' Color: yellow Height: 7.0 Width 6.0 Area: 42.0 Properties of the Second Rectangle 'r2' Color: yellow Height: 9.0 Width 5.0 Area: 45.0
See "yellow" in both r1 and r2 where as I have assigned yellow to only r2. If I remove r2 only then I can see r1's color. Help please!