简体   繁体   English

在Java中声明全局变量

[英]Declaring global variables in Java

I am making an online test web project using applets. 我正在使用applet进行在线测试Web项目。 I want to declare a variable of int type which keeps track of number of correct answers. 我想声明一个int类型的变量,它跟踪正确答案的数量。 So where is that variable required to be declared so that it can be accessed in all the frames? 那么需要声明的变量在哪里才能在所有帧中访问?

As others have mentioned, you can declare a global variable using public static : 正如其他人提到的,您可以使用public static声明一个全局变量:

public class MyClass {

    public static int globallyVisibleInt = ...;

    // or

    private static int visibleThroughAccessors = ...;

    public static void messWithGlobalState(int newValue) {
        visibleThroughAccessors = newValue;
    }

    public static int seeGlobalState() {
        return visibleThroughAccessors;
    }

}

Then to access and use this variable, any other code would merely have to import this class: 然后,要访问和使用此变量,任何其他代码只需导入此类:

// this code is inside another class and package
MyClass.globallyVisibleInt++;

// or
MyClass.messWithGlobalState(14);

However, this use of global variables is generally frowned upon. 但是, 这种全局变量的使用通常是不受欢迎的。 OOP gives you lots of tools for dealing with problems, and you probably don't need global variables for this specific case. OOP为您提供了许多处理问题的工具,您可能不需要针对此特定情况的全局变量。


Here's a good piece about avoiding global variables -- why and how. 这是一个关于避免全局变量的好文章 - 为什么以及如何。 Discussion: 讨论:

As with all HeuristicRules, this is not a rule that applies 100% of the time. 与所有HeuristicRules一样,这不是100%适用的规则。 Code is generally clearer and easier to maintain when it does not use globals, but there are exceptions. 当代码不使用全局变量时,代码通常更清晰,更容易维护,但也有例外。 It is similar in spirit to GotoConsideredHarmful, although use of global variables is less likely to get you branded as an inveterate hacker. 它在精神上类似于GotoConsideredHarmful,尽管使用全局变量不太可能让你被视为一个顽固的黑客。

Why Global Variables Should Be Avoided When Unnecessary: 为什么在不必要时应避免全局变量:

  • Non-locality 非局域
  • No Access Control or Constraint Checking 无访问控制或约束检查
  • Implicit coupling 隐含耦合
  • Concurrency issues 并发问题
  • Testing and Confinement 测试和限制

Alternatives to Global Variables: 全局变量的替代方案:

  • ContextObject ContextObject
  • Stateful Procedures 有状态程序
  • Singleton Pattern 单身模式
  • Hidden Globals 隐藏的全球

There is no global variables in java. java中没有全局变量。 You can declare public static field in some class or private static field with public static accessors 您可以使用公共静态访问器在某个类或私有静态字段中声明公共静态字段

In OOP there are no global variables, but you can declare a public static variable. OOP中没有全局变量,但您可以声明一个公共静态变量。 But this is no good practice! 但这不是好习惯! You should investigate how to handle it in your case and find another way. 您应该研究如何在您的情况下处理它并找到另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM