java - 矩形.java :35: error: non-static variable this cannot be referenced from a static context

标签 java

当我尝试编译这段代码时,我收到一条错误消息 “ Rectangle.java:35: 错误:无法从静态上下文中引用的非静态变量 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());
    }


}

最佳答案

 public static void setInDemand(boolean inDemand)
    {
        this.inDemand = inDemand;
    }

thisstatic 方法中是不允许的,因为它引用当前对象。假设一个场景,当你在不创建实例的情况下以静态方式调用此方法。这是我的意思:

Rectangle.setInDemand(true);

是对此方法的合法调用,但不是在实例上,而是使用类名。

关于java - 矩形.java :35: error: non-static variable this cannot be referenced from a static context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19173922/

相关文章:

来自另一个线程的 JavaFX webengine.executeScript()。

java - 模式 : Java class conversion from axis objects

java - 类 javax.swing.Popup 实验

java - 获取所有属性是否会在幕后进行左连接?

java - 使用 Java API 验证 X509 证书

java - 在 Spring Controller 中的请求之间共享数组列表

java - 使用插入排序和选择排序对对象数组进行排序

java - Java 初始化线程时出现拒绝访问错误

java - 使用 @WebServiceRef 进行依赖注入(inject) 我做错了。但如何呢?

java - 如何在非英语系统中初始化 Gradle 项目?