The following program should return Red color in 1 and yello in 2.But, it gives
ID: 3647490 • Letter: T
Question
The following program should return Red color in 1 and yello in 2.But, it gives yello to both.I don't know what is wrog with it.class MyRectangle
{
private double width = 1.0;
private double height = 1.0;
private static String color ="White";
public MyRectangle()
{
width = 1.0;
height = 1.0;
}
public MyRectangle(double widthParam,double heightParam, String colorParam)
{
setWidth(widthParam);
setHeight(heightParam);
setColor(colorParam);
}
public double getWidth()
{
return width;
}
public void setWidth(double widthParam)
{
width = widthParam;
}
public double getHeight()
{
return height;
}
public void setHeight(double heightParam)
{
height = heightParam;
}
public String getColor()
{
return color;
}
public static void setColor(String colorParam)
{
color = colorParam;
}
public double findArea()
{
return getWidth()*getHeight();
}
public static void main(String [] args){
MyRectangle r1 = new MyRectangle(1.5,2,"Red");
MyRectangle r2 = new MyRectangle(3,5.5,"yellow");
print(r1,1);
print (r2,2);
}
public static void print(MyRectangle r, int n)
{System.out.println("Rectangle "+n);
System.out.println("height: "+r.getHeight());
System.out.println("width: "+r.getWidth());
System.out.println("color: "+r.getColor());
System.out.println("area: "+r.findArea()+" ");
}
}
Explanation / Answer
please rate - thanks
it's because color is static, which I believe was the way it was defined in the original post
the static says that the variable coloris associated with the class, not a specific instance of that class, so all the color will be the last value
class MyRectangle
{
private double width = 1.0;
private double height = 1.0;
private String color="white";
public MyRectangle()
{
width = 1.0;
height = 1.0;
}
public MyRectangle(double widthParam,double heightParam, String colorParam)
{
setWidth(widthParam);
setHeight(heightParam);
setColor(colorParam);
}
public double getWidth()
{
return width;
}
public void setWidth(double widthParam)
{
width = widthParam;
}
public double getHeight()
{
return height;
}
public void setHeight(double heightParam)
{
height = heightParam;
}
public String getColor()
{
return color;
}
public void setColor(String colorParam)
{
color = colorParam;
}
public double findArea()
{
return getWidth()*getHeight();
}
public static void main(String [] args){
MyRectangle r1 = new MyRectangle(1.5,2,"Red");
MyRectangle r2 = new MyRectangle(3,5.5,"yellow");
print(r1,1);
print (r2,2);
}
public static void print(MyRectangle r, int n)
{System.out.println("Rectangle "+n);
System.out.println("height: "+r.getHeight());
System.out.println("width: "+r.getWidth());
System.out.println("color: "+r.getColor());
System.out.println("area: "+r.findArea()+" ");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.