public class f
{
  static int fib(int n)
  {
  if(n==0)||(n==1)
     return n;
  else
   return fib(n-2)+fib(n-1);
  }
 public static void main(String args[])
{
  int i;
 for(i=0;i<=20;i++)
     Ststem.out.print(" "+fib(i));
   Ststem.out.printIn();
}
 }
为什么第三行要用static,  

解决方案 »

  1.   

    你可以把static去掉看看能不能编译过去
      

  2.   

    main方法是静态方法,静态方法中不能调用非静态方法
      

  3.   

    因为main是static方法,要在static方法中到的成员变量或方法,都必须定义成static的
      

  4.   

    main方法是静态方法,静态方法中不能调用非静态方法,书上有说的。
      

  5.   

    不是static你就需要用这种方式调用new f().fib(i)
      

  6.   

    当声明一个对象为static时,意味着这个域或方法不会和包含这个域或方法的类中其它对象实例关联在一起。
      

  7.   

    如果不用static就要在main中生成一个实例对象句柄来引用这个fib()方法。
        因为main()方法是静态函数,在加载类前就启动了,static的变量或者方法都是可以在类加载前(或类被实例化前)被调用的,而如果fib()不是static的话,就要有一个实例对象才能调用。
      

  8.   

    是啊,你这个代码里没有创建对象的实例,
    所以自然就没有办法去调用该类中的非静态成员,
    而用static去修饰类成员的原因也在此,
      

  9.   

    java tutorial: The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in 
    ClassName.methodName(args)
    You can also refer to static methods with an object reference like 
        instanceName.methodName(args)
    but this is discouraged because it does not make it clear that they are class methods.
    Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to. 怎么理解呢?首先必须知道堆内存和栈内存!
    1:Java把内存划分成两种:一种是栈内存,一种是堆内存。栈与堆都是Java用来在Ram中存放数据的地方。
    2:在函数中定义的一些基本类型的变量和对象的引用变量都在函数的栈内存中分配。java中static变量和方法也是被分配到栈内存中的。 
    3:堆内存用来存放由new创建的对象和数组。在堆中分配的内存,由Java虚拟机的自动垃圾回收器来管理。   
    4: 栈有一个很重要的特殊性,就是存在栈中的数据可以共享。当java程序开始运行时,java虚拟机首先从main方法开始执行,main方法正是一个static方法。一个static方法只有权限去访问静态的方法,即static方法
    所以你的static int fib(int n){}必须是静态的。不知道讲清楚了没,原理很重要!很期待和大家多多讨论!
      

  10.   

     public class f 

      static int fib(int n) 
      { 
      if(n==0) ¦ ¦(n==1) 
         return n; 
      else 
       return fib(n-2)+fib(n-1); 
      } 
     public static void main(String args[]) 

      int i; 
     for(i=0;i <=20;i++) 
         Ststem.out.print(" "+fib(i)); 
       Ststem.out.printIn(); 

     } 1栈   -   有编译器自动分配释放   
    2堆   -   一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收   
    如果你的static int fib(int n) 
    不是static, 那么如果你不实例化f,操作系统就不会给int fib(int n)方法分配内存,那你想想你还可以用这个方法吗?
    所以不实例化对象,又想用类中的方法,就只能把这个方法声明为static,放到栈中就可以使用了哦。
      

  11.   

    static 可以直接调用,而不要的化,就要先实例化,才可以调用这个方法。