问答详情
源自:-

全局变量在main方法中出现不能将一个非静态变量赋值给静态变量

public class HelloWorld {

 static int var=1;//去掉static就不对了,为什么
 void call()

 { int cal;

 System.out.println("var:"+var);}

 

 void sendMessage()

 {int cal;

  System.out.println("var"+var);}

 

 public static void main(String[] args) {

    //int var=5;

    HelloWorld phone=new HelloWorld();

  phone.call();

  System.out.println(var);//为什么var一定要是static类型,如果不是static就会报错
       }

        }

提问者:Runnning_ 2015-08-09 19:45

个回答

  • 管理員
    2015-08-11 08:56:11
    已采纳

    ”不能将非静态变量赋值给静态变量“,这个一个标准的蠢货级别定义,新手很容易因为这种被蠢货总结的”经验“失去了刨根问底的动力。

    原理:

    static为类加载的时候执行,发生在创建对象之前,此时非static可以理解为还未"出生"。

    而非static需要在创建对象的时候才可以使用。

    所以如果static的方法和属性都不能调用非static,而反之可以。

  • Runnning_
    2015-08-15 10:22:27

    thanks a lot

  • 菜鸟徐
    2015-08-09 20:24:52

    main函数是static