无法从静态上下文中引用非静态变量,非静态方法

来源:互联网 发布:可口可乐销量数据表格 编辑:程序博客网 时间:2024/06/06 02:10
 
java初学者经常会遇到的问题:无法从静态上下文中引用非静态变量

non-static variable mainframe cannot be referenced from a static context
即在静态方法中不能引用非静态变量
为什么?
因为我们知道静态的方法可以在没有创建实例时使用,而申明为非静态的成员变量是一个对象属性,它只有在对象存在时引用,因此如果在对象未创建实例时我们在静态方法中调用了非静态成员方法自然是非法的,所以编译器会在这种时候给各错误.

简单说来,静态方法可以不用创建对象就调用,非静态方法必须有了对象的实例才能调用.因此想在静态方法中引用非静态方法是不可能的,因为它究竟引用的是哪个对象的非静态方法呢?编译器不可能给出答案,因为没有对象啊,所以要报错.


class HelloWorld
{
int a1 = 6;

public static void main(String[] args)
{
 
   System.out.print(a1);   
/**   成员变量不能直接调用  ( 无法从静态上下文中引用非静态变量   a1  )            
   */
}
}


编译时报如下错:

HelloWorld.java:7: 无法从静态上下文中引用非静态 变量 a1
                System.out.print(a1);
                                 ^
1 错误

因为非静态的变量a1没有初始化,改为如下程序

class HelloWorld
{
int a1 = 6;

public static void main(String[] args)
{
   HelloWorld abc=new HelloWorld();

   System.out.print(abc.a1);
}
}





编译通过。

例2:

public class Test
{
double function(int n)
{
   if (n <= 0) return 0;
   return (1.0 / n) + function(n -1);
}

public static void main(String args[])
   {
    Test a=new Test();     //在此实例化对象
   if (args.length != 1)
   {
    System.out.println("Argument Error!");
    return;
   }

   int n;
   double result;

   try
   {
    n = Integer.parseInt(args[0]);
   }
   catch(NumberFormatException e)
   {
    System.out.println("Argument is not a integer!");
    return;
   }

   result =a.function(n); //使用实例对象引用方法

   System.out.println("f(" + n + ") = " + result);
}
}
或者是:

public class Test
{
static double function(int n) //此处声明为静态方法,在对象没有创建方法即存在
{
   if (n <= 0) return 0;
   return (1.0 / n) + function(n -1);
}

public static void main(String args[])
   {
   if (args.length != 1)
   {
    System.out.println("Argument Error!");
    return;
   }

   int n;
   double result;

   try
   {
    n = Integer.parseInt(args[0]);
   }
   catch(NumberFormatException e)
   {
    System.out.println("Argument is not a integer!");
    return;
   }

   result =function(n);

   System.out.println("f(" + n + ") = " + result);
}
}
原创粉丝点击