Global variables in Java

2018-12-31 16:34发布

How do you define Global variables in Java ?

标签: java
19条回答
浮光初槿花落
2楼-- · 2018-12-31 17:11

In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program. We can have static variables to have the scope of global variables.

查看更多
其实,你不懂
3楼-- · 2018-12-31 17:13

Another way is to create an interface like this:

public interface GlobalConstants
{
  String name = "Chilly Billy";
  String address = "10 Chicken head Lane";
}

Any class that needs to use them only has to implement the interface:

public class GlobalImpl implements GlobalConstants
{
  public GlobalImpl()
  {
     System.out.println(name);
  }
}
查看更多
不流泪的眼
4楼-- · 2018-12-31 17:15

Nothing should be global, except for constants.

public class MyMainClass {
    public final static boolean DEBUGMODE=true;
}

Put this within your main class. In other .java files, use it through:

if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");

Make sure when you move your code off the cutting room floor and into release you remove or comment out this functionality.

If you have a workhorse method, like a randomizer, I suggest creating a "Toolbox" package! All coders should have one, then whenever you want to use it in a .java, just import it!

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 17:15

Generally Global variable (I assume you are comparing it with C,Cpp) define as public static final

like

class GlobalConstant{
    public static final String CODE  = "cd";
}

ENUMs are also useful in such scenario :

For Example Calendar.JANUARY)

查看更多
何处买醉
6楼-- · 2018-12-31 17:16

You don't. That's by design. You shouldn't do it even if you could.

That being said you could create a set of public static members in a class named Globals.

public class Globals {
   public static int globalInt = 0;
   ///
}

but you really shouldn't :). Seriously .. don't do it.

查看更多
旧时光的记忆
7楼-- · 2018-12-31 17:16

Truly speaking there is not a concept of "GLOBAL" in a java OO program

Nevertheless there is some truth behind your question because there will be some cases where you want to run a method at any part of the program. For example---random() method in Phrase-O-Matic app;it is a method should be callable from anywhere of a program.

So in order to satisfy the things like Above "We need to have Global-like variables and methods"

TO DECLARE A VARIABLE AS GLOBAL.

 1.Mark the variable as public static final While declaring.

TO DECLARE A METHOD AS GLOBAL.

 1. Mark the method as public static While declaring.

Because I declared global variables and method as static you can call them anywhere you wish by simply with the help of following code

ClassName.X

NOTE: X can be either method name or variable name as per the requirement and ClassName is the name of the class in which you declared them.

查看更多
登录 后发表回答