我总觉的java编译器是一句一句的编译,不在方法内的语句相互之间没有关系,而在方法内的编译是互相之间有联系,我为什么会问这个问题呢,,,,主要是有个问题是说:为什么static方法中不能使用实例变量,毕竟编译的时候没有分配内存空间啊,,,,为什么编译不通过class A 
{
   int x;
   static void poo()
   {
     x=20;
   }
}
这个时候编译没办法通过但是下面的修改后可以通过
class A
{
  int x;
  static void poo()
  {
     A a = new A();
     x=20;
  }
}
我不知道为什么会这样。因为这里new个对象也没有分配内存啊,而且执行应用程序的话也还要在main方法下再new个才行不是,所以说不知道为什么一个可以一个不可以,,,,所以这里想问问,,,java编译如何进行的?????

解决方案 »

  1.   

    下面的那个:
    class A 

      int x; 
      static void poo() 
      { 
         A a = new A(); 
         x=20; 
      } 

    是x不对,他是实例变量,不是静态变量,静态变量是被所有实例所共享的,在没有创建对象的前提下,无法确定x是哪个实例的成员,你可以这样
    class A 

      int x; 
      static void poo() 
      { 
         A a = new A(); 
         a.x=20; 
      } 

    这样就明确是a的成员了.
      

  2.   

    1 x 是属于一个实例,而你的static 不能访问实例的变量2 我看代码有误吧,应该是 a.x=20;
      

  3.   

    其实呼吁是static的用法。。
    static的修饰的方法里是不能访问非static的变量的。。
    你改了就不是访问非static变量了,就是访问对象了我不知道是不是说对了,因为本人也在学习过程中
      

  4.   

    1.static Method不能访问非static的成员(变量和方法)
    2.new是肯定会分配空间的
    3.static对象是存在于heap中,直接属于类
    一些参考资料From SCJP:
    Statics (Objective 1.3)
     
    1.Use static methods to implement behaviors that are not affected by the state of any instances.
     
    2.  
     Use static variables to hold data that is class specific as opposed to instance specific—there will be only one copy of a static variable.
     
    3.
     All static members belong to the class, not to any instance.
     
    4.
     A static method can't access an instance variable directly.
     
    5.
     Use the dot operator to access static members, but remember that using a reference variable with the dot operator is really a syntax trick, and the compiler will substitute the class name for the reference variable, for instance:d.doStuff();becomes:Dog.doStuff(); 
    6.
     static methods can't be overridden, but they can be redefinedStatic Variables and Methods (Objective 1.4)
    7.  
     They are not tied to any particular instance of a class.
     
    8.  
     No classes instances are needed in order to use static members of the class.
     
    9. 
     There is only one copy of a static variable / class and all instances share it.
     
    10.
     static methods do not have direct access to non-static members.
      
      

  5.   

    class A 

      int x; 
      static void poo() 
      { 
         A a = new A(); 
         a.x=20; 
      } 
    } 静态方法是放在方法区的,是共享的。
    而实例变量是在一个java栈中,
    该java栈是随java对象的生成而出现的。
    如果static方法调用实例变量,那么这个实例变量可能根本就不存在。
    所以编译时做了强制限制。
      

  6.   

    java的基础要学好!把类的生命周期看一下,你就明白了,关键要弄清static和实例变量的加载时机