如何在Java中定义全局变量?
当前回答
如果没有静电,这也是可能的:
class Main {
String globalVar = "Global Value";
class Class1 {
Class1() {
System.out.println("Class1: "+globalVar);
globalVar += " - changed";
} }
class Class2 {
Class2() {
System.out.println("Class2: "+globalVar);
} }
public static void main(String[] args) {
Main m = new Main();
m.mainCode();
}
void mainCode() {
Class1 o1 = new Class1();
Class2 o2 = new Class2();
}
}
/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/
其他回答
为了允许对另一个类的静态成员进行非限定访问,你也可以执行静态导入:
import static my.package.GlobalConstants;
现在,不是打印(GlobalConstants.MY_PASSWORD); 你可以直接使用常量:print(MY_PASSWORD)
“import”后面的“static”修饰符是什么意思?决定。
考虑Evan Lévesque关于承载常量的接口的回答。
很多很好的答案,但我想给出这个例子,因为它被认为是一个类访问另一个类的变量的更合适的方式:使用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;
}
}
要定义全局变量,可以使用静态关键字
public final class Tools {
public static int a;
public static int b;
}
现在您可以通过调用从任何地方访问a和b
Tools.a;
Tools.b;
你说得对……特别是在J2ME中… 可以通过将NullPointerException放入MidLet构造函数中来避免 (程序初始化)这行代码:
new Tools();
这确保了Tools将在任何指令之前分配 它使用了它。
就是这样!
从概念上讲,全局变量又称实例变量,是类级变量,即类级变量。,它们定义在类内部,但在方法之外。为了使它们完全可用,并直接使用它们,提供静态关键字。 因此,如果我正在编写一个简单的算术运算程序,它需要一个数字对,然后两个实例变量定义如下:
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关键字使我们不必反复为相同的变量指定数据类型。直接写出变量即可。
另一种方法是创建一个这样的界面:
public interface GlobalConstants
{
String name = "Chilly Billy";
String address = "10 Chicken head Lane";
}
任何需要使用它们的类只需要实现接口:
public class GlobalImpl implements GlobalConstants
{
public GlobalImpl()
{
System.out.println(name);
}
}
推荐文章
- 在流中使用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