gpt4 book ai didi

java - 创建类的新实例时,类中的静态变量是否重复?

转载 作者:搜寻专家 更新时间:2023-11-01 04:06:03 25 4
gpt4 key购买 nike

这里那里。假设我有这门课

public class EpicClass{
public static ArrayList<String> arylst = new ArrayList<>();

public String field1;
public String field2:
}

现在如果我执行这段代码:

/* ... Code which adds stuff to arylst ... */
EpicClass foo = new EpicClass();
EpicClass bar = new EpicClass();

foobar 中 ArrayList 中的内容会被复制吗??

最佳答案

没有。静态变量在类初始化时分配一次。来自Java Language Specification, §8.3.1.1 static fields :

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

请注意,这是指字段本身,而不是字段可能包含的任何值。除非该字段被声明为 final,否则您可以一个接一个地为其赋值。特别是,您可以 [mis] 使用构造函数在每次创建实例时为字段赋值。通常,您应该避免在构造函数中分配给静态字段。 (也有异常(exception),例如使用静态字段来统计实例对象的创建。)

您可以使用类名或使用对实例的引用来访问静态字段。1 因此,以下都是等价的(提供 foo bar 属于 EpicClass 类型):

EpicClass.arylst
foo.arylst
bar.arylst

(通过实例引用访问静态字段被认为是错误的,通常会生成编译器警告,但它工作得很好——即使引用为 null,因为编译器将其转换为第一种形式。)仅从这个意义上说,“ArrayList 中的内容”在该类的每个实例中似乎都是重复的。但是,ArrayList 只有一个实例,您只是通过(看似)不同的机制访问它。

1当然,前提是该字段完全可以访问。

关于java - 创建类的新实例时,类中的静态变量是否重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com