java - 如何从静态上下文引用非静态方法

标签 java constructor static

我有一个带有函数的构造函数,但是当我编译我的主方法时,我无法从静态上下文引用非静态方法区域。我知道这是一个简单的修复,但我只是无法完全到达那里。谢谢

public class Rect{
     private double x, y, width, height;

     public Rect (double x1, double newY, double newWIDTH, double newHEIGHT){
       x = x1;
       y = newY;
       width = newWIDTH;
       height = newHEIGHT;

    }
    public double area(){
       return (double) (height * width);
}

以及这个主要方法

public class TestRect{

    public static void main(String[] args){
        double x = Double.parseDouble(args[0]);
        double y = Double.parseDouble(args[1]);
        double height = Double.parseDouble(args[2]);
        double width = Double.parseDouble(args[3]);
        Rect rect = new Rect (x, y, height, width);
        double area = Rect.area();     

    }    
}

最佳答案

您需要在类的实例上调用该方法。

这段代码:

Rect rect = new Rect (x, y, height, width);
double area = Rect.area();

应该是:

Rect rect = new Rect (x, y, height, width);
double area = rect.area();
              ^ check here
                you use rect variable, not Rect class
                Java is Case Sensitive

关于java - 如何从静态上下文引用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589961/

相关文章:

java - 正则表达式 - 查找文件中的所有字符串函数参数

java - 性能:我应该避免构造函数委托(delegate)吗?

c++ - 用大括号调用构造函数

java - 使用 lombok 注释的继承会出错

c++ - 在 C++ 中使用没有对象的字符串变量调用静态类结构

C# 静态数据库类?

java - 启动器 Activity 未启动并崩溃

java - 测试 onActivityResult()

java - 使用 Java 在 HTML 页面中提取动态呈现的内容

java - 如何将枚举干净地链接到类中的静态信息?