如何在Java中定义全局变量?
当前回答
在Java中没有全局变量,但是有带有公共字段的全局类。您可以使用java 5的静态导入特性使其看起来几乎像全局变量。
其他回答
非常简单:
class UseOfGlobal
{
private static int a;
private static int b;
}
但是在方法块中尽可能地定义局部变量总是好的。
在构建面向对象编程时,要理解变量的作用域与封装这些变量的类对象紧密地独占。
创建“全局变量”的问题在于,它不是Java的行业标准。它不是行业标准,因为它允许多个类异步操作数据,如果您正在运行一个多线程应用程序,从线程安全的角度来看,这将变得更加复杂和危险。使用全局变量无效还有其他各种原因,但如果您想避免这种情况,我建议您采用面向方面编程。
面向方面编程解决了这个问题,它让父类通过所谓的“建议”来负责作用域,它在代码中添加了额外的行为,而不需要实际修改它。它为横切关注点或全局变量的使用提供解决方案。
Spring是一个利用AOP的Java框架,虽然它传统上用于web应用程序,但核心应用程序可以在整个Java框架(包括8.0)中普遍使用。这可能是你想要进一步探索的方向。
要定义全局变量,可以使用静态关键字
public class Example {
public static int a;
public static int b;
}
现在你可以在任何地方访问a和b 通过调用
Example.a;
Example.b;
// 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
一般来说,全局变量(我假设您正在与C进行比较,Cpp)定义为公共静态final
like
class GlobalConstant{
public static final String CODE = "cd";
}
enum在这样的场景中也很有用:
例如Calendar.JANUARY)
推荐文章
- 在流中使用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