静态方法:无法在静态上下文中引用非静态

来源:互联网 发布:拼豆制作软件 编辑:程序博客网 时间:2024/06/08 05:23

如上是经典的Fobonacci递归算法:

public class Fibonacci  {      public static void main(String []args)      {          int x = f(6);          System.out.println(x);      }            public int f(int x)      {          if(x==1||x==2)              return 1;          else              return f(x-1)+f(x-2);      }  } 

编译后出错,无法在静态上下文中引用非静态。

原来,在静态的方法中不能直接调用非静态的方法或属性。因为一个类的静态方法在这个Class文件被加载之后,就可以由这个Class类型对象来调用,而非静态的方法需要一个实例对象,有可能还未被创建,所以为了避免在静态方法中调用一个还不存在的实例对象的非静态方法,编译期就会直接阻止这个行为。

解决的方法有两种,第一种是将被调用的方法设置成静态方法;第二种是new本类,然后通过实例来调用。

第一种:

public class Fibonacci  {      public static void main(String []args)      {                    int x = f(6);          System.out.println(x);      }            public static int f(int x)      {          if(x==1||x==2)              return 1;          else              return f(x-1)+f(x-2);      }  }
第二种:
public class Fibonacci  {      public static void main(String []args)      {          Fibonacci f = new Fibonacci();          int x = f.f(6);          System.out.println(x);      }            public int f(int x)      {          if(x==1||x==2)              return 1;          else              return f(x-1)+f(x-2);      }  }  



阅读全文
0 0