public class hello
{
public static void main(String arg[])
{
int i=9;
System.out.print(i);
}
}
得出结果就是显示9。
可是换成下面
public class hello
{
int i=9;
public static void main(String arg[])
{
System.out.print(i);
}
}
就出错了。
non-static variable i cannot be referenced from a static context
System.out.print(i);
                 ^
1 error我是个初学的,搞不懂为什么,谁能详细的解释一下。马上结分。

解决方案 »

  1.   

    这样就可以
    public class hello
    {
    static int i=9;
    public static void main(String arg[])
    {
    System.out.print(i);
    }
    }
    这样也可以public class hello {
    int i=9;
    public static void main(String[] args) {
    hello t=new hello();
    System.out.print(t.i);
    }}
    因为hello是个类,它的非静态成员只有在类构造后才能访问
      

  2.   

    你的第二个示例中,i是 hello的数据成员,需要用对象调用,否则你就得把它声明为static int i;
    注意类名的第一个字母要大写
      

  3.   

    main函数是static类型的,不能引用非static类型的变量。可以改写成这样:
    public class hello
    {
       int i=9;
       public static void main(String arg[])
       {
           hello h = new hello();
           h.i = 9;
           System.out.print(h.i);
       }
    }