Java只允许全局变量是静态的? [英] Java only allowing global variables to be static?

查看:278
本文介绍了Java只允许全局变量是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我刚开始编写一个我正在编写的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);
}

类makeMapListener实现ActionListener {

public void actionPerformed(ActionEvent e){
$ b}
}

$ b $ <$ code>


解决方案

$ c> main 方法是 static ,所以它只能访问 static 字段该班直接。否则,您需要首先创建 PlannerMain 的实例,然后才能访问其字段。 I.e。

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

请注意,这样的初始化代码最好放在一个构造函数方法。



你引用的变量不是全局变量。现在你有许多独立的 frame 和 makeMap 多少个 PlannerMain 您创建。如果你声明它们是 public static - 在这种情况下,所有的 PlannerMain 实例将共享相同的框架 makeMap ,外部世界也会看到它们。


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?

 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) {

              }
      }

}

解决方案

Your main method is static, so it can access only the static fields of the class directly. Otherwise, you need to create an instance of PlannerMain first, then you can access its fields. I.e.

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 constructor method.

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

这篇关于Java只允许全局变量是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆