iT邦幫忙

0

java类中的静态变量

  • 分享至 

  • xImage

我想问一下类中的静态变量是否会为初始化的类添加额外的内存。

我有这样的课

public class Sample{

    public static String NAME[] = {"1", "2", "3", "4"};

    private int id;

    private String uuid;
    private String name;

    public void setUuidString() {
        UUID uuid = UUID.randomUUID();
        this.uuid = uuid.toString();
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setCustomUuid(String uuid) {
        this.uuid = uuid;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getUuid() {
        return uuid;
    }

    public String getName() {
        return name;
    }
}

我正在多次创建 Sample 类,对其进行初始化并将其添加到 Sample 类的数组中,静态变量是否会向该类添加额外的内存,或者当它是静态时它只会获得一个内存位置?

正在阅读这篇文章并引发了这个问题,所以在这里问。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2022-03-23 08:15:00

只有一個內存

你的超連結裡有寫

Static Variable in Java

The static variables are those variables that are common to all the instances
of the class; only a single copy of the static variable is created and shared
among all the instances of the class. Because it is a class-level variable,
memory allocation of such variables only happens once when the class is loaded
in the memory.

我要發表回答

立即登入回答