2014-08-31 112 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. 創建實現該方法的類的一個實例,並使用該實例調用該方法。

要選擇哪一個純粹是設計決定

相關問題