How do you define Global variables in Java ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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.
Another way is to create an interface like this:
Any class that needs to use them only has to implement the interface:
Nothing should be global, except for constants.
Put this within your main class. In other .java files, use it through:
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!
Generally Global variable (I assume you are comparing it with C,Cpp) define as
public static final
like
ENUMs are also useful in such scenario :
For Example
Calendar.JANUARY
)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.
but you really shouldn't :). Seriously .. don't do it.
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.
TO DECLARE A METHOD AS GLOBAL.
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.