Java中静态字段的确切含义是什么? [英] What is the exact meaning of static fields in Java?

查看:54
本文介绍了Java中静态字段的确切含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一类的多个对象实例之间共享一个对象.

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

从概念上讲,当我的程序运行时,A 类的所有对象都访问 B 类的同一个对象.

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

我已经看到 static 是系统范围的,不鼓励使用它.这是否意味着如果我在同一个 JVM 上运行另一个程序来实例化 A 类的对象,这些对象可能访问与前一个程序中访问的对象相同的 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)?

推荐答案

静态并不完全意味着由所有实例共享" - 它意味着与特定实例完全无关".换句话说,您无需创建任何实例即可获得 A 类中的静态字段.

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.

至于在同一个 JVM 中运行两个程序 - 这实际上取决于运行两个程序"的确切含义.静态字段有效与类对象相关联,而类对象又与类加载器相关联.因此,如果这两个程序使用单独的类加载器实例,您将拥有两个独立的静态变量.如果他们都使用相同的类加载器,那么只会有一个,这样他们就会看到彼此的更改.

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.

这篇关于Java中静态字段的确切含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆