美好的一天!初學Java - 靜態錯誤
我是Java的初學者。我不能編譯下面的代碼:出現
public class Test {
public static void main (String [] args){
int a = calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
以下錯誤:
Non-static method calcArea(int, int) cannot be referenced from static content
是什麼意思?我該如何解決這個問題..?
您的答覆將不勝感激。 謝謝您的建議基於
,我做了一個實例,它是新的測試()如下:
public class Test {
int num;
public static void main (String [] args){
Test a = new Test();
a.num = a.calcArea(7, 12);
System.out.println(a.num);
}
int calcArea(int height, int width) {
return height * width;
}
}
這是正確的嗎?有什麼區別,如果我這樣做...
public class Test {
public static void main (String [] args){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
關於你的編輯:第一,`calcArea`是一個實例方法,它在一個對象上被調用,並且(通常)執行與該對象相關的操作。第二個使`calcArea`成爲靜態(類)方法,它(通常)通常僅執行沒有任何對象實例的動作。在這裏,`calcArea`在它的參數上工作,返回一個結果,這對於類方法來說很好。現在在一個名爲`calcArea()`(無參數)的實例方法名爲Rectangle的類中,您可以看到它是如何乘以自己的高度和寬度成員變量以返回特定於對象的結果。 – 2011-01-23 15:49:02