java字段是什么意思,Java中静态字段的确切含义是什么?

在Java中,静态字段使得所有类的实例都能访问同一对象,但静态的全局范围可能导致不同程序间的意外共享。如果两个程序在同一JVM内且使用相同类加载器,它们将共享静态变量。一个替代方案是通过构造函数传递共享对象的引用,虽然这增加了实现复杂性和内存占用,但提高了测试的便利性。
摘要由CSDN通过智能技术生成

I would like to share an object between various instances of objects of the same class.

Conceptually, while my program is running, all the objects of class A access the same object of class B.

I've seen that static is system-wide and that its usage is discouraged. Does that mean that if I've got another program running on the same JVM that instantiates objects of class A, these objects could potentially access the same B object as the one accessed in the previous program?

What are generally the flaws behind using static fields?

Are there any alternatives (that do not require a huge effort of implementation)?

解决方案

Static doesn't quite mean "shared by all instances" - it means "not related to a particular instance at all". In other words, you could get at the static field in class A without ever creating any instances.

As for running two programs within the same JVM - it really depends on exactly what you mean by "running two programs". The static field is effectively associated with the class object, which is in turn associated with a classloader. So if these two programs use separate classloader instances, you'll have two independent static variables. If they both use the same classloader, then there'll only be one so they'll see each other's changes.

As for an alternative - there are various options. One is to pass the reference to the "shared" object to the constructor of each object you create which needs it. It will then need to store that reference for later. This can be a bit of a pain and suck up a bit more memory than a static approach, but it does make for easy testability.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值