我写了这样的测试代码:

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);
                           ^

我如何让我的方法识别我的类变量?


当前回答

对于所有初学者来说,解释静态关键词有点困难。 当你更多地使用类和对象时,你会清楚地了解它。

|*| Static:静态项可以用类名调用 如果你在代码中观察,有些函数是直接用类名调用的,比如

NamCls.NamFnc();

System.out.println();

这是因为NamFnc和println将在它们之前使用关键字static来声明。

|*|非静态:非静态项目可以用类变量调用 如果它不是静态的,你需要类的一个变量, 在类变量和后面加上点 然后调用function。

NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();

下面的代码简洁地解释了你

类中的静态和非静态函数:

public class NamCls
{
    public static void main(String[] args)
    {
        PlsPrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamObjVar.PrnFnc("Tst Txt");
    }

    static void PlsPrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }

    void PrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }
}

类中的静态类和非静态类:

public class NamCls
{
    public static void main(String[] args)
    {
        NamTicCls NamTicVaj = new NamTicCls();
        NamTicVaj.PrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamNicCls NamNicVar = NamObjVar.new NamNicCls();
        NamNicVar.PrnFnc("Tst Txt");
    }

    static class NamTicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }

    class NamNicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }
}

其他回答

让我们先分析一下你的程序。 在你的程序中,你的第一个方法是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).

给你们的建议是:你们误解了变量作用域和静态函数的概念。对此要有清晰的认识。

static关键字修改类中方法或变量的生命周期。静态方法或变量是在装入类时创建的。未声明为静态的方法或变量仅在类实例化为对象(例如使用new操作符)时创建。

广义来说,类的生命周期是:

类的源代码是创建模板或 图案或邮票,然后可以使用 使用类创建一个带有new操作符的对象,使类的实例作为实际对象,然后在处理对象时 在垃圾收集期间销毁对象,回收它所持有的资源,例如内存。

为了为应用程序提供一个初始入口点,Java采用了这样的约定:Java程序必须有一个类,该类包含一个具有一致同意的或特殊名称的方法。这个特殊的方法称为main()。因为无论包含main方法的类是否已被实例化,方法都必须存在,所以main()方法必须用静态修饰符声明,以便一旦装入类,main()方法就可用。

The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.

因此,您需要创建类的实例作为对象,然后可以访问未使用静态修饰符声明的类的方法和变量。一旦您的Java程序开始使用main()函数,您就可以使用任何具有static修饰符的变量或方法,因为它们作为正在加载的类的一部分存在。

However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.

import java.io.*;

class HelloWorld {
    int myInt;      // this is a class variable that is unique to each object
    static int myInt2;  // this is a class variable shared by all objects of this class

    static void main (String [] args) {
        // this is the main entry point for this Java application
        System.out.println ("Hello, World\n");
        myInt2 = 14;    // able to access the static int
        HelloWorld myWorld = new HelloWorld();
        myWorld.myInt = 32;   // able to access non-static through an object
    }
}

为了能够从静态方法中访问它们,它们需要是静态成员变量,如下所示:

public class MyProgram7 {
  static Scanner scan = new Scanner(System.in);
  static int compareCount = 0;
  static int low = 0;
  static int high = 0;
  static int mid = 0;  
  static int key = 0;  
  static Scanner temp;  
  static int[]list;  
  static String menu, outputString;  
  static int option = 1;  
  static boolean found = false;

  public static void main (String[]args) throws IOException {
  ...

I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.

静态变量被标记为静态,实例变量没有特定的关键字。