当我尝试编译此代码时,我收到一条错误消息“Rectangle.java:35: error: non-static variable this cannot be referenced from a static context this.inDemand = inDemand;”我通过将 inDemand 参数重命名为isInDemand 并在 setInDemand 方法中从 inDemand 中删除 this 前缀。我只是想了解为什么我最初所做的事情没有奏效。
代码如下:
public class Rectangle extends Polygon
{
private double height;
private static boolean inDemand = false;
private double width;
public Rectangle()
{
this(1,1,"None");
}
public Rectangle(double height, double width, String id)
{
super(id);
this.height = height;
this.width = width;
}
public double getArea()
{
return this.height*this.width;
}
public double getTotal()
{
if(inDemand == true)
{
return 2 * this.getArea();
}
else
{
return this.getArea();
}
}
public static void setInDemand(boolean inDemand)
{
this.inDemand = inDemand;
}
public static void main(String[] args)
{
Rectangle rect = new Rectangle();
rect.setInDemand(true);
System.out.println(rect.getTotal());
}
}