如何在Java中定义全局变量?
当前回答
在Java中没有全局变量
然而,我们所拥有的是一个静态关键字,这就是我们所需要的。 在Java中,类之外不存在任何东西。static关键字表示一个类变量,与实例变量相反,它只有一个副本,并且它超越了创建的该类的所有实例,这意味着它的值可以在任何时候在所有实例之间更改和访问。
如果您需要一个可以超出作用域访问的全局变量,那么这就是您需要的变量,但它的作用域只存在于类所在的位置,仅此而已。
其他回答
要定义全局变量,可以使用静态关键字
public final class Tools {
public static int a;
public static int b;
}
现在您可以通过调用从任何地方访问a和b
Tools.a;
Tools.b;
你说得对……特别是在J2ME中… 可以通过将NullPointerException放入MidLet构造函数中来避免 (程序初始化)这行代码:
new Tools();
这确保了Tools将在任何指令之前分配 它使用了它。
就是这样!
很多很好的答案,但我想给出这个例子,因为它被认为是一个类访问另一个类的变量的更合适的方式:使用getter和setter。
The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.
public class Global{
private static int var = 5;
public static int getVar(){
return Global.var;
}
//If you do not want to change the var ever then do not include this
public static void setVar(int var){
Global.var = var;
}
}
非常简单:
class UseOfGlobal
{
private static int a;
private static int b;
}
但是在方法块中尽可能地定义局部变量总是好的。
除了常量,没有什么是全局的。
public class MyMainClass {
public final static boolean DEBUGMODE=true;
}
把它放在你的主类中。在其他。java文件中,通过以下方式使用它:
if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");
确保当你把你的代码从剪辑室移出并发布时,你删除或注释掉了这个功能。
如果你有一个常用的方法,比如随机发生器,我建议你创建一个“工具箱”包!所有编码员都应该有一个,然后当你想在.java中使用它时,只需导入它!
在Java中没有全局变量,但是有带有公共字段的全局类。您可以使用java 5的静态导入特性使其看起来几乎像全局变量。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap