如何在Java中定义全局变量?
当前回答
你不。这是故意的。即使你能做,你也不应该做。
也就是说,您可以在一个名为Globals的类中创建一组公共静态成员。
public class Globals {
public static int globalInt = 0;
///
}
但你真的不应该:)。认真. .不要这样做。
其他回答
为了允许对另一个类的静态成员进行非限定访问,你也可以执行静态导入:
import static my.package.GlobalConstants;
现在,不是打印(GlobalConstants.MY_PASSWORD); 你可以直接使用常量:print(MY_PASSWORD)
“import”后面的“static”修饰符是什么意思?决定。
考虑Evan Lévesque关于承载常量的接口的回答。
public class GlobalImpl {
public static int global = 5;
}
你可以在任何地方打电话:
GlobalImpl.global // 5
// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).
// the first class
public class farm{
int eggs; // an integer to be set by constructor
fox afox; // declaration of a fox object
// the constructor inits
farm(){
eggs = 4;
afox = new fox(); // an instance of a fox object
// show count of eggs before the fox arrives
System.out.println("Count of eggs before: " + eggs);
// call class fox, afox method, pass myFarm as a reference
afox.stealEgg(this);
// show the farm class, myFarm, primitive value
System.out.println("Count of eggs after : " + eggs);
} // end constructor
public static void main(String[] args){
// instance of a farm class object
farm myFarm = new farm();
}; // end main
} // end class
// the second class
public class fox{
// theFarm is the myFarm object instance
// any public, protected, or "no modifier" variable is accessible
void stealEgg(farm theFarm){ --theFarm.eggs; }
} // end class
要定义全局变量,可以使用静态关键字
public class Example {
public static int a;
public static int b;
}
现在你可以在任何地方访问a和b 通过调用
Example.a;
Example.b;
如果没有静电,这也是可能的:
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
*/
推荐文章
- 在流中使用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