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

时间:2014-08-31 07:46:37

标签: java constructor static

我有一个带有函数的构造函数但是当我编译我的main方法时,我无法从静态上下文中引用非静态方法区域。我知道这是一个简单的解决方案我只是不能到达那里。谢谢

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();     

    }    
}

2 个答案:

答案 0 :(得分:2)

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

此代码:

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

答案 1 :(得分:0)

您有2个选项。

  1. 使方法成为静态。
  2. 创建实现该方法的类的实例,并使用该实例调用该方法。
  3. 选择哪一个纯粹是设计决策

相关问题