简体   繁体   中英

Declaring global variables in Java

I am making an online test web project using applets. I want to declare a variable of int type which keeps track of number of correct answers. 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 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.


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

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
  • Stateful Procedures
  • Singleton Pattern
  • Hidden Globals

There is no global variables in 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. But this is no good practice! You should investigate how to handle it in your case and find another way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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