2012-07-15 16 views
4

Possible Duplicate:
What is the reason behind 「non-static method cannot be referenced from a static context」?
Cannot make a static reference to the non-static method
cannot make a static reference to the non-static field無法從我無法理解什麼是錯我的代碼類型二

使靜態參考非靜態方法FXN(INT)。

class Two { 
    public static void main(String[] args) { 
     int x = 0; 

     System.out.println("x = " + x); 
     x = fxn(x); 
     System.out.println("x = " + x); 
    } 

    int fxn(int y) { 
     y = 5; 
     return y; 
    } 
} 

異常在線程「主要」 java.lang.Error的:未解決的問題,編譯: 無法從類型使靜態參考非靜態方法FXN(INT)兩個

+1

不是你的低調選民,但你會想通過[Java教程](http://docs.oracle.com/javase/tutorial/reallybigindex。HTML)或一本基礎教科書來學習Java的基礎知識。 – 2012-07-15 12:12:20

+1

如果您不瞭解我現在處於的狀況,請不要投下這個問題。 :/ 我仍然在Head First Java的第4章,並且對關於回報的陳述感到困惑。我只是想做到這一點。 – kunal 2012-07-15 12:36:44

+0

在問這個問題之前,你應該先搜索一下答案。 – 2012-07-15 13:03:41

回答

18

由於main方法是staticfxn()方法不是,所以如果不先創建Two對象,則不能調用該方法。因此,無論你改變方法:

public static int fxn(int y) { 
    y = 5; 
    return y; 
} 

main更改代碼以:在這裏Java Tutorials

Two two = new Two(); 
x = two.fxn(x); 

瞭解更多關於static

3

你可以用」由於它不是靜態的,所以不能訪問方法fxn。靜態方法只能直接訪問其他靜態方法。如果你想在你的主要方法使用FXN您需要:

... 
Two two = new Two(); 
x = two.fxn(x) 
... 

也就是說,打個雙對象,並調用該對象的方法。

...或使fxn方法靜態。

0
  1. 靜態方法不能訪問一個非靜態方法或可變的。

  2. public static void main(String[] args)是一個靜態方法,所以不能訪問非靜態public static int fxn(int y)方法。

  3. 試試這樣...

    靜態INT FXN(int y)對

    public class Two { 
    
    
        public static void main(String[] args) { 
         int x = 0; 
    
         System.out.println("x = " + x); 
         x = fxn(x); 
         System.out.println("x = " + x); 
        } 
    
        static int fxn(int y) { 
         y = 5; 
         return y; 
        } 
    

    }

1

你不能從一個靜態方法是指非靜態成員。

非靜態成員(如你的fxn(int y))只能從你的類的一個實例中調用。

例子:

你可以這樣做:

 public class A 
     { 
      public int fxn(int y) { 
       y = 5; 
       return y; 
      } 
     } 


    class Two { 
public static void main(String[] args) { 
    int x = 0; 
    A a = new A(); 
    System.out.println("x = " + x); 
    x = a.fxn(x); 
    System.out.println("x = " + x); 
} 

或者你可以宣佈你的方法是靜態的。