2014-08-31 110 views
0

我有这个构造函数,但是当我编译我的主要方法时,我无法从静态上下文中引用非静态方法区域。我知道它是一个简单的解决方案,我只是无法完成。由于如何从静态上下文中引用非静态方法

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

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

此代码:

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 
0

您有2个选项。

  1. 使方法变为静态。
  2. 创建实现该方法的类的一个实例,并使用该实例调用该方法。

要选择哪一个纯粹是设计决定

相关问题