我写了这样的测试代码:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
但它给出了以下错误:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
我如何让我的方法识别我的类变量?
让我们先分析一下你的程序。
在你的程序中,你的第一个方法是main(),记住它是静态方法…然后声明该方法的局部变量(comparate、low、high等)。这个变量的作用域只是声明的方法,不管它是静态方法还是非静态方法。你不能在这个方法之外使用这些变量。这是你犯的基本错误。
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
给你们的建议是:你们误解了变量作用域和静态函数的概念。对此要有清晰的认识。