java Java只允许全局变量是静态的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4909901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:35:00  来源:igfitidea点击:

Java only allowing global variables to be static?

javaglobal-variables

提问by TomLisankie

So I just started coding a Java program I'm writing and it's telling me that my global variables need to be static. I don't understand why it's telling me this because I've developed Java programs before without having to make my global variables static. Could someone please help?

所以我刚刚开始编写我正在编写的 Java 程序,它告诉我我的全局变量需要是静态的。我不明白为什么它会告诉我这个,因为我以前开发过 Java 程序而不必使我的全局变量静态。有人可以帮忙吗?

 import java.awt.event.*;
 import javax.swing.*;

 public class PlannerMain {
      JFrame frame;
      JButton makeMap;

      public static void main(String[] args){
           frame = new JFrame("Land Planner");
           makeMap = new JButton("Make Map");
           makeMap.addActionListener(new makeMapListener());
           frame.setSize(580,550);
           frame.setVisible(true);
      }

      class makeMapListener implements ActionListener{

              public void actionPerformed(ActionEvent e) {

              }
      }

}

回答by Péter T?r?k

Your mainmethod is static, so it can access only the staticfields of the class directly. Otherwise, you need to create an instance of PlannerMainfirst, then you can access its fields. I.e.

您的main方法是static,因此它只能static直接访问类的字段。否则,您需要先创建一个实例PlannerMain,然后才能访问其字段。IE

public static void main(String[] args){
  PlannerMain planner = new PlannerMain();
  planner.frame = new JFrame("Land Planner");
  planner.makeMap = new JButton("Make Map");
  planner.makeMap.addActionListener(new makeMapListener());
  ...
}

Note that such initialization code is better put in a constructormethod.

请注意,此类初始化代码最好放在构造函数方法中。

Btw the variables you refer to are notglobal. Right now you have as many distinct frameand makeMapas many instances of PlannerMainyou create. They would only be "global" (or its closest equivalent in Java) if you declared them public static- in this case all PlannerMaininstances would share the same frameand makeMap, and the external world would see them as well.

顺便说一句,您引用的变量不是全局变量。现在你有尽可能多的不同framemakeMap尽可能多的情况下,PlannerMain您创建。如果您声明它们,它们只会是“全局的”(或在 Java 中最接近的等价物)public static——在这种情况下,所有PlannerMain实例都将共享相同的frameand makeMap,并且外部世界也会看到它们。

回答by Pa?lo Ebermann

There are no globalvariables in Java in the meaning of variables which would be valid in the whole program.

Java 中没有全局变量的意思是在整个程序中都有效的变量。

There are

  • class variables: These are most similar to what are called "global" variables in other languages. They are declared inside a class with the statickeyword. There is only one variable for the whole class. (If the class would be loaded again with another classloader, this new class would have new variables, of course.)

    They should be used prefixed with the class: MyClass.varName. Inside of the class you also can let the prefix away, and you also could use them prefixed with an object of that type (but this is discouraged).

  • instance(or object) variables: These are what you have in your example: anything declared inside a class (and outside of any method/constructor/block) without the statickeyword is a instance variable. For each object of the containing class (which includes objects of any subclasses of this class) there is exactly one variable. (From the "state" view, one could say an object consists of all its instance variables + an identity.)

    They are used prefixed by an object (of the right type): myObject.varName. Inside of non-static methods of this class you can use them unprefixed (this is then referring to the variables of the currentobject).

  • local variables: These are all variables declared inside of a method or a constructor (or block). They exist once for each invocation of this method, and cease to exist after the method finished. They can only be accessed from inside this method, not from methods called from there.

    Special cases of these are method/constructor parameters and catch-block-parameters.

  • array elements: Every element of an array is a variable of the same type. They can be used everywhere where one has a reference to this array (often in one of the other types of variables).

  • 类变量:这些变量与其他语言中所谓的“全局”变量最为相似。它们在带有static关键字的类中声明。整个班级只有一个变量。(当然,如果用另一个类加载器再次加载该类,这个新类将有新的变量。)

    它们应该以类为前缀使用:MyClass.varName。在类内部,您也可以去掉前缀,也可以使用带有该类型对象前缀的它们(但不鼓励这样做)。

  • 实例(或对象)变量:这些是您在示例中所拥有的:在类内部(以及任何方法/构造函数/块外部)声明的任何没有static关键字的东西都是实例变量。对于包含类的每个对象(包括该类的任何子类的对象),只有一个变量。(从“状态”的角度来看,可以说一个对象由它的所有实例变量 + 一个身份组成。)

    它们以对象(正确类型)为前缀使用:myObject.varName。在此类的非静态方法中,您可以不加前缀地使用它们(这就是指当前对象的变量)。

  • 局部变量:这些都是在方法或构造函数(或块)中声明的变量。每次调用此方法时,它们都存在一次,并在方法完成后不再存在。它们只能从这个方法内部访问,不能从那里调用的方法访问。

    这些的特殊情况是方法/构造函数参数和catch-block-parameters。

  • 数组元素数组的每个元素都是相同类型的变量。它们可以在任何有对该数组的引用的地方使用(通常在其他类型的变量之一中)。

So, in your case you have object variables, and want to use them from a class method(static method). A class method has no current object, thus you have to qualify your variables with an object to use them. Depending on what you want, it may be useful to write it this way:

因此,在您的情况下,您有对象变量,并希望从类方法(静态方法)中使用它们。类方法没有当前对象,因此您必须使用对象限定变量才能使用它们。根据您的需要,以这种方式编写它可能很有用:

import java.awt.event.*;
import javax.swing.*;

public class PlannerMain {
   JFrame frame;
   JButton makeMap;

   void initGUI() {
     frame = new JFrame("Land Planner");
     makeMap = new JButton("Make Map");
     makeMap.addActionListener(new makeMapListener());
     frame.setSize(580,550);
     frame.setVisible(true);
   }

   public static void main(String[] args){
     PlannerMain pm = new PlannerMain();
     pm.initGUI();
   }
}

回答by Alb

In java the entry point - the mainmethod must be static, therefore any class variables it accesses must also be static.

在 java 中,入口点 -main方法必须是静态的,因此它访问的任何类变量也必须是静态的。

To avoid having static member variables spawn out all over the code (which is bad) from this do the following:

为了避免在整个代码中产生静态成员变量(这是不好的),请执行以下操作:

public class PlannerMain {

 JFrame frame;

 JButton makeMap;

 public static void main(String[] args){
     PlannerMain theApp = new PlannerMain();
     theApp.init();
 }

 private void init() {
     frame = new JFrame("Land Planner");
     makeMap = new JButton("Make Map");
     makeMap.addActionListener(new makeMapListener());
     frame.setSize(580,550);
     frame.setVisible(true);
 }

 class makeMapListener implements ActionListener{

    public void actionPerformed(ActionEvent e) {



        }

    }
}

Now your static mainmethod creates a concrete (non-static) instance of your PlannerMainclass so it can use the member variables.

现在,您的静态main方法创建了类的具体(非静态)实例,PlannerMain以便它可以使用成员变量。

回答by fastcodejava

It is complaining becos the mainmethod is staticand you trying to access it directly. If you create a an instance of your class PlannerMainyou can access without any problem.

它抱怨是因为该main方法是static并且您试图直接访问它。如果您创建类的实例,PlannerMain则可以毫无问题地访问。

回答by Baz1nga

if you are using some property in a static method then the property should be static. I am guessing you are using these global variables within the main method thus java is throwing this error. If you want to still access a global variable then probably define a class that is initialized with these global variables and instantiate the same in your main function and u can use it.

如果您在静态方法中使用某些属性,则该属性应该是静态的。我猜你在 main 方法中使用了这些全局变量,因此 java 抛出了这个错误。如果你仍然想访问一个全局变量,那么可能定义一个用这些全局变量初始化的类,并在你的主函数中实例化它,你可以使用它。