2012-07-15 62 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); 
} 

或者你可以宣布你的方法是静态的。