如何在Java中定义全局变量?
当前回答
从概念上讲,全局变量又称实例变量,是类级变量,即类级变量。,它们定义在类内部,但在方法之外。为了使它们完全可用,并直接使用它们,提供静态关键字。 因此,如果我正在编写一个简单的算术运算程序,它需要一个数字对,然后两个实例变量定义如下:
public class Add {
static int a;
static int b;
static int c;
public static void main(String arg[]) {
c=sum();
System.out.println("Sum is: "+c);
}
static int sum() {
a=20;
b=30;
return a+b;
}
}
Output: Sum is: 50
此外,在实例变量之前使用static关键字使我们不必反复为相同的变量指定数据类型。直接写出变量即可。
其他回答
一般来说,Java没有任何全局变量。除局部变量外,所有变量都属于程序中定义的任何类的作用域。 我们可以用静态变量来表示全局变量的作用域。
要定义全局变量,可以使用静态关键字
public class Example {
public static int a;
public static int b;
}
现在你可以在任何地方访问a和b 通过调用
Example.a;
Example.b;
为了允许对另一个类的静态成员进行非限定访问,你也可以执行静态导入:
import static my.package.GlobalConstants;
现在,不是打印(GlobalConstants.MY_PASSWORD); 你可以直接使用常量:print(MY_PASSWORD)
“import”后面的“static”修饰符是什么意思?决定。
考虑Evan Lévesque关于承载常量的接口的回答。
你最好使用依赖注入:
public class Globals {
public int a;
public int b;
}
public class UsesGlobals {
private final Globals globals;
public UsesGlobals(Globals globals) {
this.globals = globals;
}
}
很多很好的答案,但我想给出这个例子,因为它被认为是一个类访问另一个类的变量的更合适的方式:使用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;
}
}
推荐文章
- 在流中使用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